<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Media Source Extensions™</title>
    <script src="https://www.w3.org/Tools/respec/respec-w3c" class="remove"></script>
    <script src="media-source.js" class="remove"></script>
    <script class="remove">
      var respecConfig = {
      // specification status (e.g., WD, LCWD, NOTE, etc.). If in doubt use ED.
      specStatus: "ED",
      useExperimentalStyles: true,

      // the specification's short name, as in https://www.w3.org/TR/short-name/
      shortName: "media-source-2",

      // If there's a publicly available Editor's Draft, this is the link.
      // Though the 'github' respecConfig key now duplicates this functionality, this key
      // is still needed for media-source.js preprocessing for detecting if the
      // including respec source is a main spec or one of the byte-stream specs.
      edDraftURI:           "https://w3c.github.io/media-source/",

      // if this is a LCWD, uncomment and set the end of its review period
      // lcEnd: "2009-08-05",

      /* Commented out to enable auto-updating of publishDate during respec execution
      publishDate: "2016-07-26",
      */

      prevRecURI: "https://www.w3.org/TR/2016/REC-media-source-20161117/",

      editors:  [
      { name: "Matthew Wolenetz",  mailto:"wolenetz@google.com", url: "",
      company: "Google Inc.", companyURL: "https://www.google.com/",
      w3cid: "76912" },
      { name: "Mark Watson", url: "",
      company: "Netflix Inc.", companyURL: "https://www.netflix.com/",
      w3cid: "46379" },
      ],

      formerEditors: [
      { name: "Jerry Smith", note: "Until September 2017", url: "",
      company: "Microsoft Corporation", companyURL: "https://www.microsoft.com/" },
      { name: "Aaron Colwell", note: "Until April 2015",  url: "",
      company: "Google Inc.", companyURL: "https://www.google.com/" },
      { name: "Adrian Bateman", note: "Until April 2015", url: "",
      company: "Microsoft Corporation", companyURL: "https://www.microsoft.com/" },
      ],

      mseDefGroupName: "media-source",
      mseContributors: [
        "Bob Lund",
        "Alex Giladi",
        "Duncan Rowden",
        "Mark Vickers",
        "Glenn Adams",
        "Frank Galligan",
        "Steven Robertson",
        "Matt Ward",
        "David Dorwin",
        "Kevin Streeter",
        "Joe Steele",
        "Michael Thornburgh",
        "Philip Jägenstedt",
        "John Simmons",
        "Pierre Lemieux",
        "Cyril Concolato",
        "Ralph Giles",
        "David Singer",
        "Tatsuya Igarashi",
        "Chris Poole",
        "Jer Noble",
        "Matthew Gregan"
      ],

      // name of the WG
      group: "media",

      scheme: "https",

      github: "w3c/media-source",

      otherLinks: [{
      key: 'Mailing list',
      data: [{
        value: 'public-media-wg@w3.org',
        href: 'https://lists.w3.org/Archives/Public/public-media-wg/'
      }]
    },{
      key: 'Implementation',
      data: [{
        value: 'Can I use Media Source Extensions?',
        href: 'https://caniuse.com/mediasource'
      }, {
        value: 'Test Suite',
        href: 'https://w3c-test.org/media-source/'
      }, {
        value: 'Test Suite repository',
        href: 'https://github.com/web-platform-tests/wpt/tree/master/media-source'
      }]
    }],

      xref: ['fileapi'],

      preProcess: [ mediaSourcePreProcessor ],

      postProcess: [ mediaSourcePostProcessor ],
      };
    </script>

    <!-- script to register bugs -->
    <!-- Disabled unless/until it supports GitHub issues.
    <script src="https://w3c.github.io/webcomponents/assets/scripts/bug-assist.js"></script>
    <meta name="bug.short_desc" content="[MSE] ">
    <meta name="bug.product" content="HTML WG">
    <meta name="bug.component" content="Media Source Extensions">
    -->

    <link rel="stylesheet" href="mse.css">
  </head>
  <body data-cite="html dom url">
    <section id="abstract">
      This specification extends {{HTMLMediaElement}} [[HTML]] to allow
      JavaScript to generate media streams for playback.
      Allowing JavaScript to generate streams facilitates a variety of use
      cases like adaptive streaming and time shifting live streams.
    </section>

    <section id="sotd">
      <p>On top of editorial updates, substantives changes since publication as a W3C Recommendation in <a href="https://www.w3.org/TR/2016/REC-media-source-20161117/">November 2016</a> are the addition of a {{SourceBuffer/changeType()}} method to switch codecs, the possibility to create and use {{MediaSource}} objects off the main thread in dedicated workers, and the removal of the <code>createObjectURL()</code> extension to the {{URL}} object following its integration in the File API [[FILEAPI]]. For a full list of changes done since the previous version, see the <a href="https://github.com/w3c/media-source/commits/main">commits</a>.</p>

      <p>The working group maintains <a href="https://github.com/w3c/media-source/issues">a list of all bug reports that the editors have not yet tried to address</a>.</p>
      <p>Implementors should be aware that this specification is not stable. <strong>Implementors who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways.</strong> Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation stage should track the <a href="https://github.com/w3c/media-source">GitHub repository</a> and take part in the discussions.</p>
    </section>

    <section id="introduction" class="informative">
      <h2>Introduction</h2>
      <p>This specification allows JavaScript to dynamically construct media streams for &lt;audio&gt; and &lt;video&gt;. It defines a MediaSource object that can serve as a source of media data for an HTMLMediaElement. MediaSource objects have one or more <a>SourceBuffer</a> objects.  Applications append data segments to the <a>SourceBuffer</a> objects, and can adapt the quality of appended data based on system performance and other factors. Data from the <a>SourceBuffer</a> objects is managed as track buffers for audio, video and text data that is decoded and played. Byte stream specifications used with these extensions are available in the byte stream format registry [[MSE-REGISTRY]].</p>
      <a href='pipeline_model_description.html#pipelinedesc'>
        <picture><img src="pipeline_model.svg" alt="Media Source Pipeline Model Diagram"></picture>
      </a>
      <section id="goals">
        <h3>Goals</h3>
        <p>This specification was designed with the following goals in mind:</p>
        <ul>
          <li>Allow JavaScript to construct media streams independent of how the media is fetched.</li>
          <li>Define a splicing and buffering model that facilitates use cases like adaptive streaming, ad-insertion, time-shifting, and video editing.</li>
          <li>Minimize the need for media parsing in JavaScript.</li>
          <li>Leverage the browser cache as much as possible.</li>
          <li>Provide requirements for byte stream format specifications.</li>
          <li>Not require support for any particular media format or codec.</li>
        </ul>
        <p>This specification defines:</p>
        <ul>
          <li>Normative behavior for user agents to enable interoperability between user agents and web applications when processing media data.</li>
          <li>Normative requirements to enable other specifications to define media formats to be used within this specification.</li>
        </ul>
      </section>

      <section id="definitions">
        <h3>Definitions</h3>

        <dl>
          <dt><dfn id="active-track-buffers">Active Track Buffers</dfn></dt>
          <dd><p>The [=track buffers=] that provide [=coded frames=] for the {{AudioTrack/enabled}}
              {{HTMLMediaElement/audioTracks}}, the {{VideoTrack/selected}} {{HTMLMediaElement/videoTracks}}, and the
              <a def-id="texttrackmode-showing"></a> or <a def-id="texttrackmode-hidden"></a> {{HTMLMediaElement/textTracks}}. All these tracks are associated with
            <a>SourceBuffer</a> objects in the {{MediaSource/activeSourceBuffers}} list.</p>
          </dd>

          <dt><dfn id="append-window">Append Window</dfn></dt>
          <dd><p>A [=presentation timestamp=] range used to filter out [=coded frames=] while appending. The append window represents a single
            continuous time range with a single start time and end time. Coded frames with [=presentation timestamp=] within this range are allowed to be appended
            to the <a>SourceBuffer</a> while coded frames outside this range are filtered out. The append window start and end times are controlled by
            the {{SourceBuffer/appendWindowStart}} and {{SourceBuffer/appendWindowEnd}} attributes respectively.</p></dd>

          <dt><dfn id="coded-frame" data-export="">Coded Frame</dfn></dt>
          <dd><p>A unit of media data that has a [=presentation timestamp=], a [=decode timestamp=], and a [=coded frame duration=].</p></dd>

          <dt><dfn id="coded-frame-duration">Coded Frame Duration</dfn></dt>
          <dd>
            <p>The duration of a [=coded frame=]. For video and text, the duration indicates how long the video frame or text SHOULD be displayed. For audio, the duration represents the sum of all the samples contained within the coded frame. For example, if an audio frame contained 441 samples @44100Hz the frame duration would be 10 milliseconds.</p>
          </dd>

          <dt><dfn id="coded-frame-end-timestamp">Coded Frame End Timestamp</dfn></dt>
          <dd>
            <p>The sum of a [=coded frame=] [=presentation timestamp=] and its
                [=coded frame duration=]. It represents the [=presentation timestamp=] that immediately follows the coded frame.</p>
          </dd>

          <dt><dfn id="coded-frame-group">Coded Frame Group</dfn></dt>
          <dd><p>A group of [=coded frames=] that are adjacent and have monotonically increasing [=decode timestamps=] without any gaps. Discontinuities detected by the
              [=coded frame processing=] algorithm and {{SourceBuffer/abort()}} calls trigger the start of a new coded frame group.</p>
          </dd>

          <dt><dfn id="decode-timestamp">Decode Timestamp</dfn></dt>
          <dd>
            <p> The decode timestamp indicates the latest time at which the frame needs to be decoded assuming instantaneous decoding and rendering of this and any dependant frames (this is equal to the [=presentation timestamp=] of the earliest frame, in [=presentation order=], that is dependant on this frame). If frames can be decoded out of [=presentation order=], then the decode timestamp MUST be present in or derivable from the byte stream. The user agent MUST run the [=append error=] algorithm if this is not the case. If frames cannot be decoded out of  [=presentation order=] and a decode timestamp is not present in the byte stream, then the decode timestamp is equal to the [=presentation timestamp=].</p>
          </dd>

          <dt><dfn id="init-segment" data-export="">Initialization Segment</dfn></dt>
          <dd>
            <p>A sequence of bytes that contain all of the initialization information required to decode a sequence of [=media segments=]. This includes codec initialization data, [=Track ID=] mappings for multiplexed segments, and timestamp offsets (e.g., edit lists).</p>
            <p class="note">The [=byte stream format specifications=] in the byte stream format registry [[MSE-REGISTRY]] contain format specific examples.</p>

          </dd><dt><dfn id="media-segment" data-export="">Media Segment</dfn></dt>
          <dd>
            <p>A sequence of bytes that contain packetized &amp; timestamped media data for a portion of the <a def-id="media-timeline"></a>. Media segments are always associated with the most recently appended [=initialization segment=].</p>
            <p class="note">The [=byte stream format specifications=] in the byte stream format registry [[MSE-REGISTRY]] contain format specific examples.</p>
          </dd>

          <dt><dfn id="mediasource-object-url">MediaSource object URL</dfn></dt>
          <dd>
            <p>A MediaSource object URL is a unique <a def-id="blob-uri"></a> [[FILEAPI]] created by {{URL/createObjectURL()}}. It is used to attach a <a>MediaSource</a> object to an HTMLMediaElement.</p>
            <p>These URLs are the same as a <a def-id="blob-uri"></a>, except that anything in the definition of that feature that refers to <a def-id="File"></a> and <a def-id="Blob"></a> objects is hereby extended to also apply to <a>MediaSource</a> objects.</p>
            <p>The [=origin=] of the MediaSource object URL is the [=relevant settings object=] of <code>this</code> during the call to {{URL/createObjectURL()}}.</p>
            <p class="note">For example, the [=origin=] of the MediaSource object URL affects the way that the media element is <a href="https://html.spec.whatwg.org/multipage/canvas.html#security-with-canvas-elements">consumed by canvas</a>.</p>
          </dd>

          <dt><dfn id="parent-media-source">Parent Media Source</dfn></dt>
          <dd><p>The parent media source of a <a>SourceBuffer</a> object is the <a>MediaSource</a> object that created it.</p></dd>

          <dt><dfn id="presentation-start-time">Presentation Start Time</dfn></dt>
          <dd><p>The presentation start time is the earliest time point in the presentation and specifies the initial <a def-id="videoref" name="current-playback-position">playback position</a> and <a def-id="videoref" name="earliest-possible-position">earliest possible position</a>. All presentations created using this specification have a presentation start time of 0.</p>

          <p class="note">For the purposes of determining if {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} contains a {{TimeRanges}} that includes the current playback position, implementations MAY choose to allow a current playback position at or after [=presentation start time=] and before the first {{TimeRanges}} to play the first {{TimeRanges}} if that {{TimeRanges}} starts within a reasonably short time, like 1 second, after [=presentation start time=]. This allowance accommodates the reality that muxed streams commonly do not begin all tracks precisely at [=presentation start time=]. Implementations MUST report the actual buffered range, regardless of this allowance.</p>
          </dd>
          <dt><dfn id="presentation-interval">Presentation Interval</dfn></dt>
          <dd>
            <p>The presentation interval of a [=coded frame=] is the time interval from its [=presentation timestamp=] to the [=presentation timestamp=] plus the [=coded frame duration|coded frame's duration=]. For example, if a coded frame has a presentation timestamp of 10 seconds and a [=coded frame duration=] of 100 milliseconds, then the presentation interval would be [10-10.1). Note that the start of the range is inclusive, but the end of the range is exclusive.</p>
          </dd>

          <dt><dfn id="presentation-order">Presentation Order</dfn></dt>
          <dd>
            <p>The order that [=coded frames=] are rendered in the presentation. The presentation order is achieved by ordering [=coded frames=] in monotonically increasing order by their [=presentation timestamps=].</p>
          </dd>

          <dt><dfn id="presentation-timestamp" data-export="">Presentation Timestamp</dfn></dt>
          <dd>
             <p>A reference to a specific time in the presentation. The presentation timestamp in a [=coded frame=] indicates when the frame SHOULD be rendered.</p>
          </dd>

          <dt><dfn id="random-access-point" data-export="">Random Access Point</dfn></dt>
          <dd><p>A position in a [=media segment=] where decoding and continuous playback can begin without relying on any previous data in the segment. For video this tends to be the location of I-frames. In the case of audio, most audio frames can be treated as a random access point. Since video tracks tend to have a more sparse distribution of random access points, the location of these points are usually considered the random access points for multiplexed streams.</p></dd>

          <dt><dfn id="sourcebuffer-byte-stream-format-spec">SourceBuffer byte stream format specification</dfn></dt>
          <dd><p>The specific [=byte stream format specification=] that describes the format of the byte stream accepted by a <a>SourceBuffer</a> instance. The
          [=byte stream format specification=], for a <a>SourceBuffer</a> object, is initially selected based on the |type:DOMString| passed to the
          {{MediaSource/addSourceBuffer()}} call that created the object, and can be updated by {{SourceBuffer/changeType()}} calls on the object.</p></dd>

          <dt><dfn id="sourcebuffer-configuration">SourceBuffer configuration</dfn></dt>
          <dd><p>A specific set of tracks distributed across one or more <a>SourceBuffer</a>
              objects owned by a single <a>MediaSource</a> instance.</p>
            <p>Implementations MUST support at least 1 <a>MediaSource</a> object with the following
            configurations:</p>
            <ul>
              <li>A single SourceBuffer with 1 audio track and/or 1 video track.</li>
              <li>Two SourceBuffers with one handling a single audio track and the other handling a single video track.</li>
            </ul>
            <p>MediaSource objects MUST support each of the configurations above, but they are only
              required to support one configuration at a time. Supporting multiple configurations at once
              or additional configurations is a quality of implementation issue.</p>
          </dd>

          <dt><dfn id="track-description">Track Description</dfn></dt>
          <dd><p>A byte stream format specific structure that provides the [=Track ID=], codec configuration, and other metadata for a single track. Each track description inside a single [=initialization segment=] has a unique [=Track ID=]. The user agent MUST run the [=append error=] algorithm if the [=Track ID=] is not unique within the [=initialization segment=].</p></dd>

          <dt><dfn id="track-id">Track ID</dfn></dt>
          <dd><p>A Track ID is a byte stream format specific identifier that marks sections of the byte stream as being part of a specific track. The Track ID in a [=track description=] identifies which sections of a [=media segment=] belong to that track.</p></dd>

        </dl>
      </section>
    </section>

    <section id="mediasource">
      <h2><dfn>MediaSource</dfn> Object</h2>
      <p>The MediaSource object represents a source of media data for an HTMLMediaElement. It keeps track of the {{MediaSource/readyState}} for this source as well as a list of <a>SourceBuffer</a> objects that can be used to add media data to the presentation. MediaSource objects are created by the web application and then attached to an HTMLMediaElement. The application uses the <a>SourceBuffer</a> objects in {{MediaSource/sourceBuffers}} to add media data to this source. The HTMLMediaElement fetches this media data from the <a>MediaSource</a> object when it is needed during playback.</p>

      <p>Each {{MediaSource}} object has a <dfn data-dfn-for="MediaSource">[[\live seekable range]]</dfn> internal slot
        that stores a <a def-id="normalized-timeranges-object"></a>. It is initialized to an empty {{TimeRanges}} object
        when the {{MediaSource}} object is created, is maintained by {{MediaSource/setLiveSeekableRange()}} and
        {{MediaSource/clearLiveSeekableRange()}}, and is used in
        <a href="#htmlmediaelement-extensions">HTMLMediaElement Extensions</a> to modify
        {{HTMLMediaElement}}.{{HTMLMediaElement/seekable}} behavior.</p>

      <div><pre class="idl">enum ReadyState {
    "closed",
    "open",
    "ended"
};</pre><table class="simple" data-dfn-for="ReadyState"><tbody><tr><th colspan="2">Enumeration description</th></tr>
        <tr><td><dfn><code id="idl-def-ReadyState.closed">closed</code></dfn></td><td>
          Indicates the source is not currently attached to a media element.
        </td></tr>
        <tr><td><dfn><code id="idl-def-ReadyState.open">open</code></dfn></td><td>
          The source has been opened by a media element and is ready for data to be appended to the <a>SourceBuffer</a> objects in {{MediaSource/sourceBuffers}}.
        </td></tr><tr><td><dfn><code id="idl-def-ReadyState.ended">ended</code></dfn></td><td>
          The source is still attached to a media element, but {{MediaSource/endOfStream()}} has been called.
        </td></tr></tbody></table></div>

      <div class="issue" data-number="276">
          <p>Consider adding a "<code>closing</code>" {{MediaSource/ReadyState}} to indicate the source is in the process of being concurrently detached from a media element. This would be useful for some implementations of {{MediaSource}} and {{SourceBuffer}} in {{DedicatedWorkerGlobalScope}}.</p>
      </div>

      <div><pre class="idl">enum EndOfStreamError {
    "network",
    "decode"
};</pre><table class="simple" data-dfn-for="EndOfStreamError"><tbody><tr><th colspan="2">Enumeration description</th></tr><tr><td><dfn><code id="idl-def-EndOfStreamError.network">network</code></dfn></td><td>
          <p>Terminates playback and signals that a network error has occurred.</p>
          <p class="note">JavaScript applications SHOULD use this status code to terminate playback with a network error. For example, if a network error occurs while fetching media data.</p>
        </td></tr><tr><td><dfn><code id="idl-def-EndOfStreamError.decode">decode</code></dfn></td><td>
          <p>Terminates playback and signals that a decoding error has occurred.</p>
          <p class="note">JavaScript applications SHOULD use this status code to terminate playback with a decode error. For example, if a parsing error occurs while processing out-of-band media data.</p>
        </td></tr></tbody></table></div>

<pre class="idl">[Exposed=(Window,DedicatedWorker)]
interface MediaSource : EventTarget {
    constructor();
    readonly        attribute SourceBufferList    sourceBuffers;
    readonly        attribute SourceBufferList    activeSourceBuffers;
    readonly        attribute ReadyState          readyState;
                    attribute unrestricted double duration;
                    attribute EventHandler        onsourceopen;
                    attribute EventHandler        onsourceended;
                    attribute EventHandler        onsourceclose;
    static readonly attribute boolean canConstructInDedicatedWorker;
    SourceBuffer   addSourceBuffer (DOMString type);
    undefined           removeSourceBuffer (SourceBuffer sourceBuffer);
    undefined           endOfStream (optional EndOfStreamError error);
    undefined           setLiveSeekableRange (double start, double end);
    undefined           clearLiveSeekableRange ();
    static boolean isTypeSupported (DOMString type);
};</pre>
      <section>
        <h3>Attributes</h3>
        <dl class="attributes" data-dfn-for="MediaSource"><dt><dfn><code>sourceBuffers</code></dfn> of type <span class="idlAttrType"><a>SourceBufferList</a></span>, readonly       </dt><dd>
          Contains the list of <a>SourceBuffer</a> objects associated with this <a>MediaSource</a>. When {{MediaSource/readyState}} equals {{ReadyState/""closed""}} this list will be empty. Once {{MediaSource/readyState}} transitions to {{ReadyState/""open""}} SourceBuffer objects can be added to this list by using {{MediaSource/addSourceBuffer()}}.
        </dd><dt><dfn><code>activeSourceBuffers</code></dfn> of type <span class="idlAttrType"><a>SourceBufferList</a></span>, readonly       </dt><dd>
          <p>Contains the subset of {{MediaSource/sourceBuffers}} that are providing the {{VideoTrack/selected}} video track, the
            {{AudioTrack/enabled}} audio track(s), and the
            <a def-id="texttrackmode-showing"></a> or <a def-id="texttrackmode-hidden"></a> text track(s).
          </p>
          <p><a>SourceBuffer</a> objects in this list MUST appear in the same order as they appear in
            the {{MediaSource/sourceBuffers}} attribute; e.g., if only sourceBuffers[0] and
            sourceBuffers[3] are in {{MediaSource/activeSourceBuffers}}, then activeSourceBuffers[0] MUST
            equal sourceBuffers[0] and activeSourceBuffers[1] MUST equal sourceBuffers[3].
          </p>
          <p class="note">The <a href="#active-source-buffer-changes">Changes to selected/enabled track state</a> section describes how this attribute gets
            updated.</p>
        </dd><dt><dfn><code>readyState</code></dfn> of type {{ReadyState}}, readonly       </dt><dd>
          <p>Indicates the current state of the <a>MediaSource</a> object. When the <a>MediaSource</a> is created {{MediaSource/readyState}} MUST be set to {{ReadyState/""closed""}}.
        </p></dd><dt><dfn><code>duration</code></dfn> of type {{unrestricted double}}</dt><dd>
          <p>Allows the web application to set the presentation duration. The duration is initially set to NaN when the <a>MediaSource</a> object is created.</p>
          <p>On getting, run the following steps:</p>
          <ol>
            <li>If the {{MediaSource/readyState}} attribute is {{ReadyState/""closed""}} then return NaN and abort these steps.</li>
            <li>Return the current value of the attribute.</li>
          </ol>
          <p>On setting, run the following steps:</p>
          <ol>
            <li>If the value being set is negative or NaN then throw a {{TypeError}} exception and abort these steps.</li>
            <li>If the {{MediaSource/readyState}} attribute is not {{ReadyState/""open""}} then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true on any <a>SourceBuffer</a> in {{MediaSource/sourceBuffers}}, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>Run the [=duration change=] algorithm with |new duration:unrestricted double| set to the value being assigned to this attribute.
              <p class="note">The [=duration change=] algorithm will adjust |new duration| higher if there is any currently buffered coded frame with a higher end time.</p>
              <p class="note">{{SourceBuffer/appendBuffer()}} and {{MediaSource/endOfStream()}} can update the duration under certain circumstances.</p>
            </li>
          </ol>
        </dd><dt><dfn><code>onsourceopen</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{sourceopen}} event.</p>
        </dd><dt><dfn><code>onsourceended</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{sourceended}} event.</p>
        </dd><dt><dfn><code>onsourceclose</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{sourceclose}} event.</p>
        </dd>
        <dt><dfn><code>canConstructInDedicatedWorker</code></dfn> of type {{boolean}}</dt><dd>
          <p>Returns true.</p>
          <p class="note">This attribute enables main thread and dedicated worker feature detection of support for
            creating and using a {{MediaSource}} object in a dedicated worker, and mitigates the need for higher latency
            detection polyfills like attempting creation of a {{MediaSource}} object from a dedicated worker, especially
            if the feature is not supported.</p>
        </dd></dl></section><section><h2>Methods</h2><dl class="methods" data-dfn-for="MediaSource"><dt><dfn><code>addSourceBuffer</code></dfn></dt><dd>
          <p>Adds a new <a>SourceBuffer</a> to {{MediaSource/sourceBuffers}}.</p>
          <ol class="method-algorithm">
            <li>If |type:DOMString| is an empty string then throw a {{TypeError}} exception and abort these steps.</li>
            <li>If |type| contains a MIME type that is not supported or contains a MIME type that is not supported with the types specified for the other <a>SourceBuffer</a> objects in {{MediaSource/sourceBuffers}}, then throw a {{NotSupportedError}} exception and abort these steps.</li>
            <li>If the user agent can't handle any more SourceBuffer objects or if creating a SourceBuffer
              based on |type| would result in an unsupported [=SourceBuffer configuration=],
              then throw a {{QuotaExceededError}} exception and abort these steps.
              <p class="note">For example, a user agent MAY throw a {{QuotaExceededError}} exception if the media element has reached the
                {{HTMLMediaElement/HAVE_METADATA}} readyState. This can occur if the user agent's media engine does not support adding more tracks during
                playback.
              </p>
            </li>
            <li>If the {{MediaSource/readyState}} attribute is not in the {{ReadyState/""open""}} state then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>Create a new <a>SourceBuffer</a> object and associated resources.</li>
            <li>Set the {{SourceBuffer/[[generate timestamps flag]]}} on the new object to the value in the "Generate
              Timestamps Flag" column of the byte stream format registry [[MSE-REGISTRY]] entry that is associated with
              |type|.
            </li><li>
              <dl class="switch">
                <dt>If the {{SourceBuffer/[[generate timestamps flag]]}} equals true:</dt>
                <dd>
                  Set the {{SourceBuffer/mode}} attribute on the new object to
                  {{AppendMode/""sequence""}}.
                </dd>
                <dt>Otherwise:</dt>
                <dd>
                  Set the {{SourceBuffer/mode}} attribute on the new object to
                  {{AppendMode/""segments""}}.
                </dd>
              </dl>
            </li>
            <li>Add the new object to {{MediaSource/sourceBuffers}} and [=queue a task=] to [=fire an event=] named {{addsourcebuffer}} at {{MediaSource/sourceBuffers}}.</li>
            <li>Return the new object.</li>
          </ol>
        <table class="parameters"><tbody><tr><th>Parameter</th><th>Type</th><th>Nullable</th><th>Optional</th><th>Description</th></tr><tr><td class="prmName">|type|</td><td class="prmType">{{DOMString}}</td><td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td><td class="prmOptFalse"><span role="img" aria-label="False">✘</span></td><td class="prmDesc"></td></tr></tbody></table><div><em>Return type: </em><a>SourceBuffer</a></div></dd>

          <dt><dfn><code>removeSourceBuffer</code></dfn></dt><dd>
          <p>Removes a {{SourceBuffer}} from {{MediaSource/sourceBuffers}}.</p>

          <ol class="method-algorithm">
            <li>If |sourceBuffer:SourceBuffer| specifies an object that is not in {{MediaSource/sourceBuffers}} then throw a {{NotFoundError}} exception and abort these steps.</li>
            <li>If the |sourceBuffer|.{{SourceBuffer/updating}} attribute equals true, then run the following steps:
              <ol>
                <li>Abort the [=buffer append=] algorithm if it is running.</li>
                <li>Set the |sourceBuffer|.{{SourceBuffer/updating}} attribute to false.</li>
                <li>[=Queue a task=] to [=fire an event=] named {{abort}} at |sourceBuffer|.</li>
                <li>[=Queue a task=] to [=fire an event=] named {{updateend}} at |sourceBuffer|.</li>
              </ol>
            </li>

            <li>Let |SourceBuffer audioTracks list:AudioTrackList| equal the {{AudioTrackList}} object returned by
              |sourceBuffer|.{{SourceBuffer/audioTracks}}.</li>
            <li>If the |SourceBuffer audioTracks list| is not empty, then run the following steps:
              <ol>
                <li>For each {{AudioTrack}} object in the |SourceBuffer audioTracks list|, run the following steps:
                  <ol>
                    <li>Set the {{AudioTrack/sourceBuffer}} attribute on the {{AudioTrack}} object to null.</li>

                    <li>Remove the {{AudioTrack}} object from the |SourceBuffer audioTracks list|.
                    <p class="note">
                      This should trigger {{AudioTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=]
                      named [=AudioTrackList/removetrack=] using {{TrackEvent}} with the {{TrackEvent/track}}
                      attribute initialized to the {{AudioTrack}} object, at the |SourceBuffer audioTracks list|.
                      If the {{AudioTrack/enabled}} attribute on the {{AudioTrack}} object was true at the beginning
                      of this removal step, then this should also trigger {{AudioTrackList}} [[HTML]] logic to
                      [=queue a task=] to [=fire an event=] named [=AudioTrackList/change=] at the
                      |SourceBuffer audioTracks list|.
                    </p>
                    </li>

                    <li>
                      <dl class="switch">
                        <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                        <dd>Post an internal <code>remove track mirror</code> message to {{MediaSource/[[port to
                        main]]}} whose implicit handler in {{Window}} runs the steps in the following "otherwise" case
                        for the {{Window}} {{AudioTrack}} mirror of the {{DedicatedWorkerGlobalScope}} {{AudioTrack}}
                        object created previously by the implicit handler for the internal <code>create track
                        mirror</code> message.</dd>
                        <dt>Otherwise, run the following steps:</dt>
                        <dd>
                        <ol>
                          <li>Let |HTMLMediaElement audioTracks list:AudioTrackList| equal the {{AudioTrackList}} object
                            returned by the {{HTMLMediaElement/audioTracks}} attribute on the HTMLMediaElement.</li>
                          <li>Remove the {{AudioTrack}} object from the |HTMLMediaElement audioTracks list|.
                            <p class="note">
                              This should trigger {{AudioTrackList}} [[HTML]] logic to [=queue a task=] to
                              [=fire an event=] named [=AudioTrackList/removetrack=] using {{TrackEvent}} with the
                              {{TrackEvent/track}} attribute initialized to the {{AudioTrack}} object, at the
                              |HTMLMediaElement audioTracks list|. If the {{AudioTrack/enabled}} attribute on the
                              {{AudioTrack}} object was true at the beginning of this removal step, then this should
                              also trigger {{AudioTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=]
                              named [=AudioTrackList/change=] at the |HTMLMediaElement audioTracks list|.
                            </p>
                          </li>
                        </ol>
                        </dd>
                      </dl>
                    </li>
                  </ol>
                </li>
              </ol>
            </li>

            <li>Let |SourceBuffer videoTracks list:VideoTrackList| equal the {{VideoTrackList}} object returned by
              |sourceBuffer|.{{SourceBuffer/videoTracks}}.</li>
            <li>If the |SourceBuffer videoTracks list| is not empty, then run the following steps:
              <ol>
                <li>For each {{VideoTrack}} object in the |SourceBuffer videoTracks list|, run the following steps:
                  <ol>
                    <li>Set the {{VideoTrack/sourceBuffer}} attribute on the {{VideoTrack}} object to null.</li>

                    <li>Remove the {{VideoTrack}} object from the |SourceBuffer videoTracks list|.
                    <p class="note">
                      This should trigger {{VideoTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=]
                      named [=VideoTrackList/removetrack=] using {{TrackEvent}} with the {{TrackEvent/track}}
                      attribute initialized to the {{VideoTrack}} object, at the |SourceBuffer videoTracks list|.
                      If the {{VideoTrack/selected}} attribute on the
                      {{VideoTrack}} object was true at the beginning of this removal step, then this should also
                      trigger {{VideoTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=] named
                      [=VideoTrackList/change=] at the |SourceBuffer videoTracks list|.
                    </p>
                    </li>

                    <li>
                      <dl class="switch">
                        <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                        <dd>Post an internal <code>remove track mirror</code> message to {{MediaSource/[[port to
                        main]]}} whose implicit handler in {{Window}} runs the steps in the following "otherwise" case
                        for the {{Window}} {{VideoTrack}} mirror of the {{DedicatedWorkerGlobalScope}} {{VideoTrack}}
                        object created previously by the implicit handler for the internal <code>create track
                        mirror</code> message.</dd>
                        <dt>Otherwise, run the following steps:</dt>
                        <dd>
                        <ol>
                          <li>Let |HTMLMediaElement videoTracks list:VideoTrackList| equal the {{VideoTrackList}} object
                            returned by the {{HTMLMediaElement/videoTracks}} attribute on the HTMLMediaElement.</li>
                          <li>Remove the {{VideoTrack}} object from the |HTMLMediaElement videoTracks list|.
                            <p class="note">
                              This should trigger {{VideoTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=]
                              named [=VideoTrackList/removetrack=] using {{TrackEvent}} with the {{TrackEvent/track}}
                              attribute initialized to the {{VideoTrack}} object, at the |HTMLMediaElement videoTracks list|.
                              If the
                              {{VideoTrack/selected}} attribute on the {{VideoTrack}} object was true at the beginning
                              of this removal step, then this should also trigger {{VideoTrackList}} [[HTML]] logic to
                              [=queue a task=] to [=fire an event=] named [=VideoTrackList/change=] at the
                              |HTMLMediaElement videoTracks list|.
                            </p>
                          </li>
                        </ol>
                        </dd>
                      </dl>
                    </li>
                  </ol>
                </li>
              </ol>
            </li>

            <li>Let |SourceBuffer textTracks list:TextTrackList| equal the {{TextTrackList}} object returned by
              |sourceBuffer|.{{SourceBuffer/textTracks}}.</li>
            <li>If the |SourceBuffer textTracks list| is not empty, then run the following steps:
              <ol>
                <li>For each {{TextTrack}} object in the |SourceBuffer textTracks list|, run the following steps:
                  <ol>
                    <li>Set the {{TextTrack/sourceBuffer}} attribute on the {{TextTrack}} object to null.</li>

                    <li>Remove the {{TextTrack}} object from the |SourceBuffer textTracks list|.
                    <p class="note">
                      This should trigger {{TextTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=]
                      named [=TextTrackList/removetrack=] using {{TrackEvent}} with the {{TrackEvent/track}}
                      attribute initialized to the {{TextTrack}} object, at the |SourceBuffer textTracks list|.
                      If the {{TextTrack/mode}} attribute on the
                      {{TextTrack}} object was <a def-id="texttrackmode-showing"></a> or
                      <a def-id="texttrackmode-hidden"></a> at the beginning of this removal step, then this should also
                      trigger {{TextTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=] named
                      [=TextTrackList/change=] at the |SourceBuffer textTracks list|.
                    </p>
                    </li>

                    <li>
                      <dl class="switch">
                        <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                        <dd>Post an internal <code>remove track mirror</code> message to {{MediaSource/[[port to
                        main]]}} whose implicit handler in {{Window}} runs the steps in the following "otherwise" case
                        for the {{Window}} {{TextTrack}} mirror of the {{DedicatedWorkerGlobalScope}} {{TextTrack}}
                        object created previously by the implicit handler for the internal <code>create track
                        mirror</code> message.</dd>
                        <dt>Otherwise, run the following steps:</dt>
                        <dd>
                        <ol>
                          <li>Let |HTMLMediaElement textTracks list:TextTrackList| equal the {{TextTrackList}} object
                            returned by the {{HTMLMediaElement/textTracks}} attribute on the HTMLMediaElement.</li>
                          <li>Remove the {{TextTrack}} object from the |HTMLMediaElement textTracks list|.
                            <p class="note">
                              This should trigger {{TextTrackList}} [[HTML]] logic to [=queue a task=] to [=fire an event=]
                              named [=TextTrackList/removetrack=] using {{TrackEvent}} with the {{TrackEvent/track}}
                              attribute initialized to the {{TextTrack}} object, at the |HTMLMediaElement textTracks list|.
                              If the
                              {{TextTrack/mode}} attribute on the {{TextTrack}} object was
                              <a def-id="texttrackmode-showing"></a> or <a def-id="texttrackmode-hidden"></a> at the
                              beginning of this removal step, then this should also trigger {{TextTrackList}} [[HTML]]
                              logic to [=queue a task=] to [=fire an event=] named [=TextTrackList/change=]
                              at the |HTMLMediaElement textTracks list|.
                            </p>
                          </li>
                        </ol>
                        </dd>
                      </dl>
                    </li>
                  </ol>
                </li>
              </ol>
            </li>

            <li>If |sourceBuffer| is in {{MediaSource/activeSourceBuffers}}, then remove |sourceBuffer| from
              {{MediaSource/activeSourceBuffers}} and [=queue a task=] to [=fire an event=] named {{removesourcebuffer}}
              at the <a>SourceBufferList</a> returned by {{MediaSource/activeSourceBuffers}}.</li>
            <li>Remove |sourceBuffer| from {{MediaSource/sourceBuffers}} and [=queue a task=] to [=fire an event=] named
              {{removesourcebuffer}} at the <a>SourceBufferList</a> returned by {{MediaSource/sourceBuffers}}.</li>
            <li>Destroy all resources for |sourceBuffer|.</li>
          </ol>
        <table
          class="parameters"><tbody><tr><th>Parameter</th><th>Type</th><th>Nullable</th><th>Optional</th><th>Description</th></tr><tr><td class="prmName">|sourceBuffer|</td><td class="prmType">{{SourceBuffer}}</td><td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td><td class="prmOptFalse"><span role="img" aria-label="False">✘</span></td><td class="prmDesc"></td></tr></tbody></table><div><em>Return type: </em>{{undefined}}</div></dd>

          <dt><dfn><code>endOfStream</code></dfn></dt><dd>
          <p>Signals the end of the stream.</p>

          <ol class="method-algorithm">
            <li>If the {{MediaSource/readyState}} attribute is not in the {{ReadyState/""open""}} state then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true on any <a>SourceBuffer</a> in {{MediaSource/sourceBuffers}}, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>Run the [=end of stream=] algorithm with the error parameter set to |error:EndOfStreamError|.</li>
          </ol>
        <table
          class="parameters"><tbody><tr><th>Parameter</th><th>Type</th><th>Nullable</th><th>Optional</th><th>Description</th></tr><tr><td class="prmName">|error|</td><td class="prmType">{{EndOfStreamError}}</td><td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td><td class="prmOptTrue"><span role="img" aria-label="True">✔</span></td><td class="prmDesc"></td></tr></tbody></table><div><em>Return type: </em>{{undefined}}</div></dd>

          <dt><dfn><code>setLiveSeekableRange</code></dfn></dt><dd>

          <p>Updates {{MediaSource/[[live seekable range]]}} that is used in
            <a href="#htmlmediaelement-extensions">HTMLMediaElement Extensions</a> to modify
            {{HTMLMediaElement}}.{{HTMLMediaElement/seekable}} behavior.</p>
          <ol class="method-algorithm">
            <li>If the {{MediaSource/readyState}} attribute is not {{ReadyState/""open""}} then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If |start:double| is negative or greater than |end:double|, then throw a {{TypeError}} exception and abort these steps.</li>
            <li>Set {{MediaSource/[[live seekable range]]}} to be a new <a def-id="normalized-timeranges-object"></a>
              containing a single range whose start position is |start| and end position is |end|.
          </li></ol>
          <table class="parameters">
            <tbody>
              <tr>
                <th>Parameter</th>
                <th>Type</th>
                <th>Nullable</th>
                <th>Optional</th>
                <th>Description</th>
              </tr>
              <tr>
                <td class="prmName">|start|</td>
                <td class="prmType">{{double}}</td>
                <td class="prmNullFalse"><span aria-label="False" role=
                "img">✘</span></td>
                <td class="prmOptFalse"><span aria-label="False" role=
                "img">✘</span></td>
                <td class="prmDesc">The start of the range, in seconds measured from [=presentation start time=]. While set, and if {{MediaSource/duration}} equals positive Infinity, {{HTMLMediaElement}}.{{HTMLMediaElement/seekable}} will return a non-empty TimeRanges object with a lowest range start timestamp no greater than |start|.</td>
              </tr>
              <tr>
                <td class="prmName">|end|</td>
                <td class="prmType">{{double}}</td>
                <td class="prmNullFalse"><span aria-label="False" role=
                "img">✘</span></td>
                <td class="prmOptFalse"><span aria-label="False" role=
                "img">✘</span></td>
                <td class="prmDesc">The end of range, in seconds measured from [=presentation start time=]. While set, and if {{MediaSource/duration}} equals positive Infinity, {{HTMLMediaElement}}.{{HTMLMediaElement/seekable}} will return a non-empty TimeRanges object with a highest range end timestamp no less than |end|.</td>
              </tr>
            </tbody>
          </table>
        <div><em>Return type: </em>{{undefined}}</div></dd><dt><dfn><code>clearLiveSeekableRange</code></dfn></dt><dd>
        <p>Updates {{MediaSource/[[live seekable range]]}} that is used in
          <a href="#htmlmediaelement-extensions">HTMLMediaElement Extensions</a> to modify
          {{HTMLMediaElement}}.{{HTMLMediaElement/seekable}} behavior.</p>

          <ol class="method-algorithm">
            <li>If the {{MediaSource/readyState}} attribute is not {{ReadyState/""open""}} then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If {{MediaSource/[[live seekable range]]}} contains a range, then set {{MediaSource/[[live seekable
              range]]}} to be a new empty {{TimeRanges}} object.
          </li></ol>
        <div><em>No parameters.</em></div><div><em>Return type: </em>{{undefined}}</div></dd><dt><dfn><code>isTypeSupported</code></dfn>, static</dt><dd>
          <p>Check to see whether the <a>MediaSource</a> is capable of creating <a>SourceBuffer</a> objects for the specified MIME type.</p>

          <ol class="method-algorithm">
            <li>If |type:DOMString| is an empty string, then return false.</li>
            <li>If |type| does not contain a valid MIME type string, then return false.</li>
            <li>If |type| contains a media type or media subtype that the MediaSource does not support, then return false.</li>
            <li>If |type| contains a codec that the MediaSource does not support, then return false.</li>
            <li>If the MediaSource does not support the specified combination of media type, media subtype, and codecs then return false.</li>
            <li>Return true.</li>
          </ol>
          <p class="note">
            If true is returned from this method, it only indicates that the <a>MediaSource</a> implementation is capable of creating <a>SourceBuffer</a> objects for the specified MIME type. An {{MediaSource/addSourceBuffer()}} call SHOULD still fail if sufficient resources are not available to support the addition of a new <a>SourceBuffer</a>.
          </p>
          <p class="note">
            This method returning true implies that HTMLMediaElement.canPlayType() will return "maybe" or "probably" since it does not make sense for a <a>MediaSource</a> to support a type the HTMLMediaElement knows it cannot play.
          </p>
        <table class="parameters"><tbody><tr><th>Parameter</th><th>Type</th><th>Nullable</th><th>Optional</th><th>Description</th></tr><tr><td class="prmName">|type|</td><td class="prmType">{{DOMString}}</td><td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td><td class="prmOptFalse"><span role="img" aria-label="False">✘</span></td><td class="prmDesc"></td></tr></tbody></table><div><em>Return type: </em>{{boolean}}</div></dd></dl>
      </section>

      <section id="mediasource-events">
        <h3>Event Summary</h3>
        <table class="old-table">
          <thead>
            <tr>
              <th>Event name</th>
              <th>Interface</th>
              <th>Dispatched when...</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><dfn><code>sourceopen</code></dfn></td>
              <td><code>Event</code></td>
              <td>{{MediaSource/readyState}} transitions from {{ReadyState/""closed""}} to {{ReadyState/""open""}} or from {{ReadyState/""ended""}} to {{ReadyState/""open""}}.</td>
            </tr>
            <tr>
              <td><dfn><code>sourceended</code></dfn></td>
              <td><code>Event</code></td>
              <td>{{MediaSource/readyState}} transitions from {{ReadyState/""open""}} to {{ReadyState/""ended""}}.</td>
            </tr>
            <tr>
              <td><dfn><code>sourceclose</code></dfn></td>
              <td><code>Event</code></td>
              <td>{{MediaSource/readyState}} transitions from {{ReadyState/""open""}} to {{ReadyState/""closed""}} or {{ReadyState/""ended""}} to {{ReadyState/""closed""}}.</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section id="mediasource-in-worker-communication-model">
        <h3><dfn>Cross-context communication model</dfn></h3>

        <p>When a {{Window}} {{HTMLMediaElement}} is attached to a {{DedicatedWorkerGlobalScope}} {{MediaSource}}, each context
        has algorithms that depend on information from the other.</p>

        <p class="note">{{HTMLMediaElement}} is exposed only to {{Window}} contexts, but {{MediaSource}} and related objects defined
        in this specification are exposed in {{Window}} and {{DedicatedWorkerGlobalScope}} contexts. This lets
        applications construct a {{MediaSource}} object in either of those types of context and attach it to an
        {{HTMLMediaElement}} object in a {{Window}} context using a [=MediaSource object URL=] as described in the
        [=attaching to a media element=] algorithm. A {{MediaSource}} object is not {{Transferable}}; it is only visible
        in the context where it was created.</p>

        The rest of this section describes a model for bounding information latency for attachments of a {{Window}}
        media element to a {{DedicatedWorkerGlobalScope}} {{MediaSource}}. While the model describes communication using
        message passing, implementations MAY choose to communicate in potentially faster ways, such as using shared
        memory and locks. Attachments to a {{Window}} {{MediaSource}} synchronously have the information already without
        communicating it across contexts.

        <p>A {{MediaSource}} that is constructed in a {{DedicatedWorkerGlobalScope}} has a
        <dfn data-dfn-for="MediaSource">[[\port to main]]</dfn> internal slot that stores a {{MessagePort}} setup during
        attachment and nulled during detachment. A {{Window}} {{MediaSource/[[port to main]]}} is always null.</p>

        </p>An {{HTMLMediaElement}} extended by this specification and attached to a {{DedicatedWorkerGlobalScope}}
        {{MediaSource}} similarly has a <dfn data-dfn-for="HTMLMediaElement">[[\port to worker]]</dfn> internal slot
        that stores a {{MessagePort}} and a <dfn data-dfn-for="HTMLMediaElement">[[\channel with worker]]</dfn> internal
        slot that stores a {{MessageChannel}}, both setup during attachment and nulled during detachment. Both
        {{HTMLMediaElement/[[port to worker]]}} and {{HTMLMediaElement/[[channel with worker]]}} are null unless
        attached to a {{DedicatedWorkerGlobalScope}} {{MediaSource}}.</p>

        <p>Algorithms in this specification that need to communicate information from a {{Window}} {{HTMLMediaElement}}
        to an attached {{DedicatedWorkerGlobalScope}} {{MediaSource}}, or vice versa, will use these internal ports
        implicitly to post a message to their counterpart, where the implicit handler of the message runs steps as
        described in the algorithms.</p>
      </section>

      <section id="mediasource-algorithms">
        <h3>Algorithms</h3>

        <section id="mediasource-attach">
          <h4><dfn>Attaching to a media element</dfn></h4>
          <p> A <a>MediaSource</a> object can be attached to a media element by assigning a [=MediaSource object URL=] to the media element {{HTMLMediaElement/src}} attribute or the src attribute of a &lt;source&gt; inside a media element. A [=MediaSource object URL=] is created by passing a MediaSource object to {{URL/createObjectURL()}}.</p>

          <p>If the <a def-id="resource-fetch-algorithm"></a> was invoked with
          a media provider object that is a MediaSource object or a URL record whose object is a MediaSource object,
          then let mode be local, skip the first step in the <a def-id="resource-fetch-algorithm"></a>
          (which may otherwise set mode to remote) and add the steps and clarifications below to the <a def-id="Otherwise-mode-is-local"></a> section of the <a def-id="resource-fetch-algorithm"></a>.
          <p class="note">The <a def-id="resource-fetch-algorithm"></a>'s first step is expected to eventually align with selecting local mode for URL records whose objects are media provider objects. The intent is that if the HTMLMediaElement's <code>src</code> attribute or selected child <code>&lt;source&gt;</code>'s <code>src</code> attribute is a <code>blob:</code> URL matching a [=MediaSource object URL=] when the respective <code>src</code> attribute was last changed, then that MediaSource object is used as the media provider object and current media resource in the local mode logic in the <a def-id="resource-fetch-algorithm"></a>. This also means that the remote mode logic that includes observance of any preload attribute is skipped when a MediaSource object is attached. Even with that eventual change to [[HTML]], the execution of the following steps at the beginning of the local mode logic is still required when the current media resource is a MediaSource object.</p>
          <p class="note">Relative to the action which triggered the media element's resource selection algorithm, these steps are asynchronous. The resource fetch algorithm is run after the task that invoked the resource selection algorithm is allowed to continue and a stable state is reached. Implementations may delay the steps in the "<i>Otherwise</i>" clause, below, until the MediaSource object is ready for use.</p>
          <dl class="switch">
            <dt>If {{MediaSource/readyState}} is NOT set to {{ReadyState/""closed""}}</dt>
            <dd>Run the <a def-id="media-data-cannot-be-fetched"></a> steps of the <a def-id="resource-fetch-algorithm"></a>'s <a def-id="media-data-processing-steps-list"></a>.</dd>
            <dt>Otherwise</dt>
            <dd>
              <ol>
                <li>Set the media element's <a def-id="delaying-the-load-event-flag"></a> to false.</li>
                <li>
                  <dl class="switch">
                    <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}, then setup worker
                    attachment communication and open the {{MediaSource}}:</dt>
                    <dd><ol>
                      <li>Set {{HTMLMediaElement/[[channel with worker]]}} to be a new {{MessageChannel}}.</li>
                      <li>Set {{HTMLMediaElement/[[port to worker]]}} to the {{MessageChannel/port1}} value of
                        {{HTMLMediaElement/[[channel with worker]]}}.</li>
                      <li>Execute [=StructuredSerializeWithTransfer=] with the {{MessageChannel/port2}} of
                        {{HTMLMediaElement/[[channel with worker]]}} as both the value and the sole member of the |transferList|, and let
                        the result be |serialized port2:MessagePort|.
                      <li>[=Queue a task=] on the {{MediaSource}}'s {{DedicatedWorkerGlobalScope}} that will
                        <ol>
                          <li>Execute [=StructuredDeserializeWithTransfer=] with |serialized port2| and
                            {{DedicatedWorkerGlobalScope}}'s [=environment settings object/realm=], and set
                            {{MediaSource/[[port to main]]}} to be the resulting deserialized clone of the transferred
                            {{MessageChannel/port2}} value of {{HTMLMediaElement/[[channel with worker]]}}.</li>
                          <li>Set the {{MediaSource/readyState}} attribute to {{ReadyState/""open""}}.</li>
                          <li>[=Queue a task=] to [=fire an event=] named {{sourceopen}} at the <a>MediaSource</a>.</li>
                        </ol>
                      </li>
                    </ol></dd>
                    <dt>Otherwise, the {{MediaSource}} was constructed in a {{Window}}:</dt>
                    <dd><ol>
                      <li>Set {{HTMLMediaElement/[[channel with worker]]}} null.</li>
                      <li>Set {{HTMLMediaElement/[[port to worker]]}} null.</li>
                      <li>Set {{MediaSource/[[port to main]]}} null.</li>
                      <li>Set the {{MediaSource/readyState}} attribute to {{ReadyState/""open""}}.</li>
                      <li>[=Queue a task=] to [=fire an event=] named {{sourceopen}} at the <a>MediaSource</a>.</li>
                    </ol></dd>
                  </dl>
                <li>Continue the <a def-id="resource-fetch-algorithm"></a> by running the remaining <a def-id="Otherwise-mode-is-local"></a> steps, with these clarifications:
                  <ol>
                    <li>Text in the <a def-id="resource-fetch-algorithm"></a> or the <a def-id="media-data-processing-steps-list"></a> that refers to "the download", "bytes received", or "whenever new data for the current media resource becomes available" refers to data passed in via {{SourceBuffer/appendBuffer()}}.</li>
                    <li>References to HTTP in the <a def-id="resource-fetch-algorithm"></a> and the <a def-id="media-data-processing-steps-list"></a> do not apply because the HTMLMediaElement does not fetch media data via HTTP when a <a>MediaSource</a> is attached.</li>
                  </ol>
                </li>
              </ol>
            </dd>
          </dl>
          <p class="note">An attached MediaSource does not use the remote mode steps in the <a def-id="resource-fetch-algorithm"></a>, so the media element will not fire "suspend" events. Though future versions of this specification will likely remove "progress" and "stalled" events from a media element with an attached MediaSource, user agents conforming to this version of the specification may still fire these two events as these [[HTML]] references changed after implementations of this specification stabilized.</p>
        </section>

        <section id="mediasource-detach">
          <h4><dfn>Detaching from a media element</dfn></h4>
          <p>The following steps are run in any case where the media element is going to transition to {{HTMLMediaElement/NETWORK_EMPTY}} and [=queue a task=] to [=fire an event=] named   [=HTMLMediaElement/emptied=] at the media element. These steps SHOULD be run right before the transition.</p>

          <ol>
            <li>
              <dl class="switch">
                <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                <dd><ol>
                  <li>Notify the {{MediaSource}} using an internal <code>detach</code> message posted to
                    {{HTMLMediaElement/[[port to worker]]}}.</li>
                  <li>Set {{HTMLMediaElement/[[port to worker]]}} null.</li>
                  <li>Set {{HTMLMediaElement/[[channel with worker]]}} null.</li>
                  <li>The implicit message handler for this <code>detach</code> notification runs the remainder of these
                    steps in the {{DedicatedWorkerGlobalScope}} {{MediaSource}}.</li>
                </ol></dd>
                <dt>Otherwise, the {{MediaSource}} was constructed in a {{Window}}:</dt>
                <dd>Continue the remainder of these steps on the {{Window}} {{MediaSource}}.</dd>
              </dl></li>
            <li>Set {{MediaSource/[[port to main]]}} null.</li>
            <li>Set the {{MediaSource/readyState}} attribute to {{ReadyState/""closed""}}.</li>
            <li>Update {{MediaSource/duration}} to NaN.</li>
            <li>Remove all the <a>SourceBuffer</a> objects from {{MediaSource/activeSourceBuffers}}.</li>
            <li>
              [=Queue a task=] to [=fire an event=] named {{removesourcebuffer}} at {{MediaSource/activeSourceBuffers}}.</li>
            <li>Remove all the <a>SourceBuffer</a> objects from {{MediaSource/sourceBuffers}}.</li>
            <li>
              [=Queue a task=] to [=fire an event=] named {{removesourcebuffer}} at {{MediaSource/sourceBuffers}}.</li>
            <li>
              [=Queue a task=] to [=fire an event=] named {{sourceclose}} at the <a>MediaSource</a>.</li>
          </ol>
          <p class="note">Going forward, this algorithm is intended to be externally called and run in any case where the attached <a>MediaSource</a>, if any, must be detached from the media element.  It MAY be called on HTMLMediaElement [[HTML]] operations like load() and resource fetch algorithm failures in addition to, or in place of, when the media element transitions to {{HTMLMediaElement/NETWORK_EMPTY}}. Resource fetch algorithm failures are those which abort either the resource fetch algorithm or the resource selection algorithm, with the exception that the "Final step" [[HTML]] is not considered a failure that triggers detachment.</p>
        </section>

        <section id="mediasource-seeking">
          <h4><dfn>Seeking</dfn></h4>
          <p>Run the following steps as part of the "<i>Wait until the user agent has established whether or not the media data for the new playback position is available, and, if it is, until it has decoded enough data to play back that position"</i> step of the <a def-id="hme-seek-algorithm"></a>:</p>
          <ol>
            <li>
            <p class="note">The media element looks for [=media segments=] containing the |new playback position:double| in each <a>SourceBuffer</a> object in {{MediaSource/activeSourceBuffers}}.
            Any position within a {{TimeRanges}} in the current value of the {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} attribute has all necessary media segments buffered for that position.</p>
              <dl class="switch">
                <dt>If |new playback position| is not in any {{TimeRanges}} of {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}}</dt>
                  <dd>
                  <ol>
                    <li>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is greater than
                      {{HTMLMediaElement/HAVE_METADATA}}, then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute
                      to {{HTMLMediaElement/HAVE_METADATA}}.
                    <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
                    </li>
                    <li>The media element waits until an {{SourceBuffer/appendBuffer()}} call causes the [=coded frame processing=] algorithm to set
                      the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to a value greater than {{HTMLMediaElement/HAVE_METADATA}}.
                      <p class="note">The web application can use {{SourceBuffer/buffered}} and {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} to determine what the media element needs to resume playback.</p>
                    </li>
                  </ol>
                </dd>
                <dt>Otherwise</dt>
                <dd>Continue
                <p class="note">If the {{MediaSource/readyState}} attribute is {{ReadyState/""ended""}} and the |new playback position| is within a {{TimeRanges}} currently in {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}}, then the seek operation must continue to completion here even if one or more currently selected or enabled track buffers' largest range end timestamp is less than |new playback position|. This condition should only occur due to logic in {{SourceBuffer/buffered}} when {{MediaSource/readyState}} is {{ReadyState/""ended""}}.</p>
                </dd>
              </dl>
            </li>
            <li>The media element resets all decoders and initializes each one with data from the appropriate [=initialization segment=].</li>
            <li>The media element feeds [=coded frames=] from the [=active track buffers=] into the decoders starting with the
              closest [=random access point=] before the |new playback position|.</li>
            <li>Resume the <a def-id="hme-seek-algorithm"></a> at the "<i>Await a stable state</i>" step.</li>
          </ol>
        </section>

        <section id="buffer-monitoring">
          <h4><dfn>SourceBuffer Monitoring</dfn></h4>
          <p>The following steps are periodically run during playback to make sure that all of the <a>SourceBuffer</a> objects in {{MediaSource/activeSourceBuffers}} have [=enough data to ensure uninterrupted playback=]. Changes to {{MediaSource/activeSourceBuffers}} also cause these steps to run because they affect the conditions that trigger state transitions.</p>

          <p>Having <dfn id="enough-data">enough data to ensure uninterrupted playback</dfn> is an implementation specific condition where the user agent
          determines that it currently has enough data to play the presentation without stalling for a meaningful period of time. This condition is
          constantly evaluated to determine when to transition the media element into and out of the {{HTMLMediaElement/HAVE_ENOUGH_DATA}} ready state.
          These transitions indicate when the user agent believes it has enough data buffered or it needs more data respectively.</p>

          <p class="note">An implementation MAY choose to use bytes buffered, time buffered, the append rate, or any other metric it sees fit to
            determine when it has enough data. The metrics used MAY change during playback so web applications SHOULD only rely on the value of
            {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} to determine whether more data is needed or not.</p>

          <p class="note">When the media element needs more data, the user agent SHOULD transition it from {{HTMLMediaElement/HAVE_ENOUGH_DATA}} to
            {{HTMLMediaElement/HAVE_FUTURE_DATA}} early enough for a web application to be able to respond without causing an interruption in playback.
            For example, transitioning when the current playback position is 500ms before the end of the buffered data gives the application roughly
            500ms to append more data before playback stalls.</p>

          <dl class="switch">
            <dt>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute equals {{HTMLMediaElement/HAVE_NOTHING}}:</dt>
            <dd>
              <ol>
                <li>Abort these steps.</li>
              </ol>
            </dd>
            <dt>If {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} does not contain a {{TimeRanges}} for the current playback position:</dt>
            <dd>
              <ol>
                <li>Set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_METADATA}}.
                <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p></li>
                <li>Abort these steps.</li>
              </ol>
            </dd>
            <dt>If {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} contains a {{TimeRanges}} that includes the current playback position and [=enough data to ensure uninterrupted playback=]:</dt>
            <dd>
              <ol>
                <li>Set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_ENOUGH_DATA}}.
                <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p></li>
                <li>Playback may resume at this point if it was previously suspended by a transition to {{HTMLMediaElement/HAVE_CURRENT_DATA}}.</li>
                <li>Abort these steps.</li>
              </ol>
            </dd>
            <dt>If {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} contains a {{TimeRanges}} that includes the current playback position and some time beyond the current playback position, then run the following steps:</dt>
            <dd>
              <ol>
                <li>Set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_FUTURE_DATA}}.
                <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
                </li>
                <li>Playback may resume at this point if it was previously suspended by a transition to {{HTMLMediaElement/HAVE_CURRENT_DATA}}.</li>
                <li>Abort these steps.</li>
              </ol>
            </dd>
            <dt>If {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} contains a {{TimeRanges}} that ends at the current playback position and does not have a range covering the time immediately after the current position:</dt>
            <dd>
              <ol>
                <li>Set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_CURRENT_DATA}}.
                <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
                </li>
                <li>Playback is suspended at this point since the media element doesn't have enough data to advance the <a def-id="media-timeline"></a>.</li>
                <li>Abort these steps.</li>
              </ol>
            </dd>
          </dl>
        </section>

        <section id="active-source-buffer-changes">
          <h4><dfn>Changes to selected/enabled track state</dfn></h4>
          <p>During playback {{MediaSource/activeSourceBuffers}} needs to be updated if the {{VideoTrack/selected}} video track, the {{AudioTrack/enabled}} audio track(s), or a text track {{TextTrack/mode}} changes. When one or more of these changes occur the following steps need to be followed.
             Also, when {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}, then each change that occurs
             to a {{Window}} mirror of a track created previously by the implicit handler for the internal <code>create
               track mirror</code> message MUST also be made to the corresponding {{DedicatedWorkerGlobalScope}} track
             using an internal <code>update track state</code> message posted to {{HTMLMediaElement/[[port to worker]]}}
             whose implicit handler makes the change and runs the following steps.
             Likewise, each change that occurs to a {{DedicatedWorkerGlobalScope}} track MUST also be made to the
             corresponding {{Window}} mirror of the track using an internal <code>update track state</code> message
             posted to {{MediaSource/[[port to main]]}} whose implicit handler makes the change to the mirror.
          </p>
          <dl class="switch">
            <dt>If the selected video track changes, then run the following steps:</dt>
            <dd>
              <ol>
                <li>If the <a>SourceBuffer</a> associated with the previously selected video track is not associated with any other enabled tracks, run the following steps:
                  <ol>
                    <li>Remove the <a>SourceBuffer</a> from {{MediaSource/activeSourceBuffers}}.</li>
                    <li>
                      [=Queue a task=] to [=fire an event=] named {{removesourcebuffer}} at {{MediaSource/activeSourceBuffers}}
                    </li>
                  </ol>
                </li>
                <li>If the <a>SourceBuffer</a> associated with the newly selected video track is not already in {{MediaSource/activeSourceBuffers}}, run the following steps:
                  <ol>
                    <li>Add the <a>SourceBuffer</a> to {{MediaSource/activeSourceBuffers}}.</li>
                    <li>
                      [=Queue a task=] to [=fire an event=] named {{addsourcebuffer}} at {{MediaSource/activeSourceBuffers}}
                    </li>
                  </ol>
                </li>
              </ol>
            </dd>
            <dt>If an audio track becomes disabled and the <a>SourceBuffer</a> associated with this track is not associated with any other enabled or selected track, then run the following steps:</dt>
            <dd>
              <ol>
                <li>Remove the <a>SourceBuffer</a> associated with the audio track from {{MediaSource/activeSourceBuffers}}
                </li>
                <li>
                  [=Queue a task=] to [=fire an event=] named {{removesourcebuffer}} at {{MediaSource/activeSourceBuffers}}
                </li>
              </ol>
            </dd>
            <dt>If an audio track becomes enabled and the <a>SourceBuffer</a> associated with this track is not already in {{MediaSource/activeSourceBuffers}}, then run the following steps:
            </dt>
            <dd>
              <ol>
                <li>Add the <a>SourceBuffer</a> associated with the audio track to {{MediaSource/activeSourceBuffers}}
                </li>
                <li>
                  [=Queue a task=] to [=fire an event=] named {{addsourcebuffer}} at {{MediaSource/activeSourceBuffers}}
                </li>
              </ol>
            </dd>
            <dt>If a text track {{TextTrack/mode}} becomes <a def-id="texttrackmode-disabled"></a> and the <a>SourceBuffer</a> associated with this track is not associated with any other enabled or selected track, then run the following steps:</dt>
            <dd>
              <ol>
                <li>Remove the <a>SourceBuffer</a> associated with the text track from {{MediaSource/activeSourceBuffers}}
                </li>
                <li>
                  [=Queue a task=] to [=fire an event=] named {{removesourcebuffer}} at {{MediaSource/activeSourceBuffers}}
                </li>
              </ol>
            </dd>
            <dt>If a text track {{TextTrack/mode}} becomes <a def-id="texttrackmode-showing"></a> or <a def-id="texttrackmode-hidden"></a> and the <a>SourceBuffer</a> associated with this track is not already in {{MediaSource/activeSourceBuffers}}, then run the following steps:
            </dt>
            <dd>
              <ol>
                <li>Add the <a>SourceBuffer</a> associated with the text track to {{MediaSource/activeSourceBuffers}}
                </li>
                <li>
                  [=Queue a task=] to [=fire an event=] named {{addsourcebuffer}} at {{MediaSource/activeSourceBuffers}}
                </li>
              </ol>
            </dd>
          </dl>
        </section>

        <section id="duration-change-algorithm">
          <h4><dfn>Duration change</dfn></h4>
          <p>Follow these steps when {{MediaSource/duration}} needs to change to a |new duration:unrestricted double|.</p>
          <ol>
            <li>If the current value of {{MediaSource/duration}} is equal to |new duration|, then return.</li>
            <li>If |new duration| is less than the highest [=presentation timestamp=] of any buffered [=coded frames=] for all <a>SourceBuffer</a> objects in {{MediaSource/sourceBuffers}}, then throw an {{InvalidStateError}} exception and abort these steps.
            <p class="note">Duration reductions that would truncate currently buffered media are disallowed. When truncation is necessary, use {{SourceBuffer/remove()}} to reduce the buffered range before updating {{MediaSource/duration}}.</p>
            </li>
            <li>Let |highest end time:unrestricted double| be the largest [=track buffer ranges=] end time across all the [=track buffers=] across all <a>SourceBuffer</a> objects in {{MediaSource/sourceBuffers}}.</li>
            <li>If |new duration| is less than |highest end time|, then
              <p class="note">This condition can occur because the [=coded frame removal=] algorithm preserves coded frames that start before the start of the removal range.</p>
              <ol>

                <li>Update |new duration| to equal |highest end time|.</li>
              </ol>
            </li>
            <li>Update {{MediaSource/duration}} to |new duration|.</li>
            <li>Update the {{HTMLMediaElement/duration}} to |new duration|.</li>
            <li>
              <dl class="switch">
                <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                <dd>Post an internal <code>duration change</code> message to {{MediaSource//[[port to main]]}} whose
                implicit handler in {{Window}} runs the <a def-id="hme-duration-change-algorithm"></a>.</dd>
                <dt>Otherwise:</dt>
                <dd>Run the <a def-id="hme-duration-change-algorithm"></a>.</dd>
              </dl>
            </li>
          </ol>
        </section>

        <section id="end-of-stream-algorithm">
          <h4><dfn>End of stream</dfn></h4>
          <p>This algorithm gets called when the application signals the end of stream via an {{MediaSource/endOfStream()}} call or an algorithm needs to
            signal a decode error. This algorithm takes an |error:EndOfStreamError| parameter that indicates whether an error will be signalled.</p>
          <ol>
            <li>Change the {{MediaSource/readyState}} attribute value to {{ReadyState/""ended""}}.</li>
            <li>
              [=Queue a task=] to [=fire an event=] named {{sourceended}} at the <a>MediaSource</a>.</li>
            <li><dl class="switch">
                <dt>If |error| is not set</dt>
                <dd>
                  <ol>
                    <li>Run the [=duration change=] algorithm with |new duration:unrestricted double| set to
                      the largest [=track buffer ranges=] end time across all the [=track buffers=] across all <a>SourceBuffer</a> objects in {{MediaSource/sourceBuffers}}.
                      <p class="note">This allows the duration to properly reflect the end of the appended media segments. For example, if the duration was explicitly set to 10 seconds and only media segments for 0 to 5 seconds were appended before endOfStream() was called, then the duration will get updated to 5 seconds.</p>
                    </li>
                    <li>Notify the media element that it now has all of the media data.</li>
                  </ol>
                </dd>

                <dt>If |error| is set to {{EndOfStreamError/""network""}}</dt>
                <dd>
                <dl class="switch">
                  <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                  <dd>Post an internal <code>network error</code> message to {{MediaSource//[[port to main]]}} whose
                  implicit handler in {{Window}} runs the steps in the following "otherwise" case.</dd>
                  <dt>Otherwise:</dt>
                  <dd>
                  <dl class="switch">
                    <dt>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute equals
                    {{HTMLMediaElement/HAVE_NOTHING}}</dt>
                    <dd>Run the <a def-id="media-data-cannot-be-fetched"></a> steps of the <a def-id="resource-fetch-algorithm"></a>'s <a def-id="media-data-processing-steps-list"></a>.</dd>
                    <dt>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is greater than
                    {{HTMLMediaElement/HAVE_NOTHING}}</dt>
                    <dd>Run the "<i>If the connection is interrupted after some media data has been received, causing the user agent to give up trying to fetch the resource</i>" steps of the <a def-id="resource-fetch-algorithm"></a>'s <a def-id="media-data-processing-steps-list"></a>.</dd>
                  </dl>
                  </dd>
                </dl>
                </dd>

                <dt>If |error| is set to {{EndOfStreamError/""decode""}}</dt>
                <dd>
                <dl class="switch">
                  <dt>If the {{MediaSource}} was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                  <dd>Post an internal <code>decode error</code> message to {{MediaSource/[[port to main]]}} whose
                  implicit handler in {{Window}} runs the steps in the following "otherwise" case.</dd>
                  <dt>Otherwise:</dt>
                  <dd>
                  <dl class="switch">
                    <dt>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute equals
                    {{HTMLMediaElement/HAVE_NOTHING}}</dt>
                    <dd>Run the "<i>If the media data can be fetched but is found by inspection to be in an unsupported format, or can otherwise not be rendered at all</i>" steps of the <a def-id="resource-fetch-algorithm"></a>'s <a def-id="media-data-processing-steps-list"></a>.</dd>
                    <dt>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is greater than
                    {{HTMLMediaElement/HAVE_NOTHING}}
                    <dd>Run the <a def-id="media-data-is-corrupted"></a> steps of the <a def-id="resource-fetch-algorithm"></a>'s <a def-id="media-data-processing-steps-list"></a>.</dd>
                  </dl>
                  </dd>
                </dl>
                </dd>
              </dl>
            </li>
          </ol>
        </section>
      </section>
    </section>

    <section id="sourcebuffer">
      <h2><dfn>SourceBuffer</dfn> Object</h2>


<pre class="idl">enum AppendMode {
    "segments",
    "sequence"
};</pre><table class="simple" data-dfn-for="AppendMode"><tbody><tr><th colspan="2">Enumeration description</th></tr><tr><td><dfn><code id="idl-def-AppendMode.segments">segments</code></dfn></td><td>
          <p>The timestamps in the media segment determine where the [=coded frames=] are placed in the presentation. Media segments can be appended in any order.</p>
        </td></tr><tr><td><dfn><code id="idl-def-AppendMode.sequence">sequence</code></dfn></td><td>
          <p>Media segments will be treated as adjacent in time independent of the timestamps in the media segment. Coded frames in a new media segment will be placed immediately after the coded
            frames in the previous media segment. The {{SourceBuffer/timestampOffset}} attribute will be updated if a new offset is needed to make the new media segments adjacent to the previous media segment.
            Setting the {{SourceBuffer/timestampOffset}} attribute in {{AppendMode/""sequence""}} mode allows a media segment to be placed at a specific position in the timeline without any knowledge
            of the timestamps in the media segment.
          </p>
        </td></tr></tbody></table>

<pre class="idl">[Exposed=(Window,DedicatedWorker)]
interface SourceBuffer : EventTarget {
                    attribute AppendMode          mode;
    readonly        attribute boolean             updating;
    readonly        attribute TimeRanges          buffered;
                    attribute double              timestampOffset;
    readonly        attribute AudioTrackList      audioTracks;
    readonly        attribute VideoTrackList      videoTracks;
    readonly        attribute TextTrackList       textTracks;
                    attribute double              appendWindowStart;
                    attribute unrestricted double appendWindowEnd;
                    attribute EventHandler        onupdatestart;
                    attribute EventHandler        onupdate;
                    attribute EventHandler        onupdateend;
                    attribute EventHandler        onerror;
                    attribute EventHandler        onabort;
    undefined appendBuffer (BufferSource data);
    undefined abort ();
    undefined changeType (DOMString type);
    undefined remove (double start, unrestricted double end);
};</pre>
          <div class="issue" data-number="280">[[HTML]] {{AudioTrackList}}, {{VideoTrackList}} and {{TextTrackList}} need Window+DedicatedWorker
          exposure.</div>
          <section><h2>Attributes</h2><dl class="attributes" data-dfn-for="SourceBuffer"><dt><dfn><code>mode</code></dfn> of type <a>AppendMode</a></dt><dd>
          <p>Controls how a sequence of [=media segments=] are handled. This attribute is initially set by {{MediaSource/addSourceBuffer()}} after the object is created, and can be updated by {{SourceBuffer/changeType()}} or setting this attribute.</p>
          <p>On getting, Return the initial value or the last value that was successfully set.</p>
          <p>On setting, run the following steps:</p>
          <ol>
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=], then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>Let |new mode:AppendMode| equal the new value being assigned to this attribute.</li>
            <li>If {{SourceBuffer/[[generate timestamps flag]]}} equals true and |new mode| equals
              {{AppendMode/""segments""}}, then throw a {{TypeError}} exception and abort these steps.</li>
            <li>
              <p>If the {{MediaSource/readyState}} attribute of the [=parent media source=] is in the {{ReadyState/""ended""}} state then run the following steps:</p>
              <ol>
                <li>Set the {{MediaSource/readyState}} attribute of the [=parent media source=] to {{ReadyState/""open""}}</li>
                <li>[=Queue a task=] to [=fire an event=] named {{sourceopen}} at the [=parent media source=].</li>
              </ol>
            </li>
            <li>If the {{SourceBuffer/[[append state]]}} equals [=PARSING_MEDIA_SEGMENT=], then throw an
              {{InvalidStateError}} and abort these steps.</li>
            <li>If the |new mode| equals {{AppendMode/""sequence""}}, then set the {{SourceBuffer/[[group start
              timestamp]]}} to the {{SourceBuffer/[[group end timestamp]]}}.</li>
            <li>Update the attribute to |new mode|.</li>
          </ol>
        </dd><dt><dfn><code>updating</code></dfn> of type {{boolean}}, readonly       </dt><dd>
          <p>Indicates whether the asynchronous continuation of an {{SourceBuffer/appendBuffer()}} or {{SourceBuffer/remove()}}
            operation is still being processed. This attribute is initially set to false when the object is created.</p>
        </dd><dt><dfn><code>buffered</code></dfn> of type {{TimeRanges}}, readonly       </dt><dd>
          <p>Indicates what {{TimeRanges}} are buffered in the <a>SourceBuffer</a>. This
          attribute is initially set to an empty {{TimeRanges}} object when the object is
          created.</p>
          <p>When the attribute is read the following steps MUST occur:</p>
          <ol>
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=] then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>Let |highest end time:double| be the largest [=track buffer ranges=] end time across all the [=track buffers=] managed by this <a>SourceBuffer</a> object.</li>
            <li>Let |intersection ranges:normalized TimeRanges| equal a {{TimeRanges}} object containing a single range from 0 to |highest end time|.</li>
            <li>For each audio and video [=track buffer=] managed by this <a>SourceBuffer</a>, run the following steps:
                <p class="note">Text [=track buffers=] are included in the calculation of |highest end time|, above, but excluded from the buffered range calculation here. They are not necessarily continuous, nor should any discontinuity within them trigger playback stall when the other media tracks are continuous over the same time range.</p>
              <ol>
                <li>Let |track ranges:normalized TimeRanges| equal the [=track buffer ranges=] for the current [=track buffer=].</li>
                <li>If {{MediaSource/readyState}} is {{ReadyState/""ended""}}, then set the end time on the last range in |track ranges| to |highest end time|.</li>
                <li>Let |new intersection ranges:normalized TimeRanges| equal the intersection between the |intersection ranges| and the |track ranges|.</li>
                <li>Replace the ranges in |intersection ranges| with the |new intersection ranges|.</li>
              </ol>
            </li>
            <li>If |intersection ranges| does not contain the exact same range information as the
              current value of this attribute, then update the current value of this attribute to
              |intersection ranges|.</li>
            <li>Return the current value of this attribute.</li>
          </ol>
        </dd><dt><dfn><code>timestampOffset</code></dfn> of type {{double}}</dt><dd>
          <p>Controls the offset applied to timestamps inside subsequent [=media segments=] that are appended to this <a>SourceBuffer</a>. The {{SourceBuffer/timestampOffset}} is initially set to 0 which indicates that no offset is being applied.</p>
          <p>On getting, Return the initial value or the last value that was successfully set.</p>
          <p>On setting, run the following steps:</p>
          <ol>
            <li>Let |new timestamp offset:double| equal the new value being assigned to this attribute.</li>
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=], then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>
              <p>If the {{MediaSource/readyState}} attribute of the [=parent media source=] is in the {{ReadyState/""ended""}} state then run the following steps:</p>
              <ol>
                <li>Set the {{MediaSource/readyState}} attribute of the [=parent media source=] to {{ReadyState/""open""}}</li>
                <li>[=Queue a task=] to [=fire an event=] named {{sourceopen}} at the [=parent media source=].</li>
              </ol>
            </li>
            <li>If the {{SourceBuffer/[[append state]]}} equals [=PARSING_MEDIA_SEGMENT=], then throw an
              {{InvalidStateError}} and abort these steps.</li>
            <li>If the {{SourceBuffer/mode}} attribute equals {{AppendMode/""sequence""}}, then set the
              {{SourceBuffer/[[group start timestamp]]}} to |new timestamp offset|.</li>
            <li>Update the attribute to |new timestamp offset|.</li>
          </ol>
        </dd><dt><dfn><code>audioTracks</code></dfn> of type {{AudioTrackList}}, readonly       </dt><dd>
          The list of {{AudioTrack}} objects created by this object.
        </dd><dt><dfn><code>videoTracks</code></dfn> of type {{VideoTrackList}}, readonly       </dt><dd>
          The list of {{VideoTrack}} objects created by this object.
        </dd><dt><dfn><code>textTracks</code></dfn> of type {{TextTrackList}}, readonly       </dt><dd>
          The list of {{TextTrack}} objects created by this object.
        </dd><dt><dfn><code>appendWindowStart</code></dfn> of type {{double}}</dt><dd>
          <p>The [=presentation timestamp=] for the start of the [=append window=]. This attribute is initially set to the [=presentation start time=].</p>
          <p>On getting, Return the initial value or the last value that was successfully set.</p>
          <p>On setting, run the following steps:</p>
          <ol>
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=], then throw an
              {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the new value is less than 0 or greater than or equal to {{SourceBuffer/appendWindowEnd}} then throw a {{TypeError}} exception
              and abort these steps.</li>
            <li>Update the attribute to the new value.</li>
          </ol>
        </dd><dt><dfn><code>appendWindowEnd</code></dfn> of type {{unrestricted double}}</dt><dd>
          <p>The [=presentation timestamp=] for the end of the [=append window=]. This attribute is initially set to positive Infinity.</p>
          <p>On getting, Return the initial value or the last value that was successfully set.</p>
          <p>On setting, run the following steps:</p>
          <ol>
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=], then throw an
              {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the new value equals NaN, then throw a {{TypeError}} and abort these steps.</li>
            <li>If the new value is less than or equal to {{SourceBuffer/appendWindowStart}} then throw a {{TypeError}} exception and abort these
              steps.</li>
            <li>Update the attribute to the new value.</li>
          </ol>
        </dd><dt><dfn><code>onupdatestart</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{updatestart}} event.</p>
        </dd><dt><dfn><code>onupdate</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{update}} event.</p>
        </dd><dt><dfn><code>onupdateend</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{updateend}} event.</p>
        </dd><dt><dfn><code>onerror</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{error}} event.</p>
        </dd><dt><dfn><code>onabort</code></dfn> of type {{EventHandler}}</dt><dd>
          <p>The event handler for the {{abort}} event.</p>
        </dd></dl></section><section><h2>Methods</h2><dl class="methods" data-dfn-for="SourceBuffer"><dt><dfn id="dom-sourcebuffer-appendbuffer"><code>appendBuffer</code></dfn></dt><dd>
            <p>Appends the segment data in an <a class="externalDFN">BufferSource</a>[[!WEBIDL]] to the {{SourceBuffer}}.</p>

          <ol class="method-algorithm">
            <li>Run the [=prepare append=] algorithm.</li>
            <li>Add |data:BufferSource| to the end of the {{SourceBuffer/[[input buffer]]}}.</li>
            <li>Set the {{SourceBuffer/updating}} attribute to true.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{updatestart}} at this <a>SourceBuffer</a> object.</li>
            <li>Asynchronously run the [=buffer append=] algorithm.</li>
          </ol>
        <table class="parameters"><tbody><tr><th>Parameter</th><th>Type</th><th>Nullable</th><th>Optional</th><th>Description</th></tr><tr><td class="prmName">|data|</td><td class="prmType">{{BufferSource}}</td><td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td><td class="prmOptFalse"><span role="img" aria-label="False">✘</span></td><td class="prmDesc"></td></tr></tbody></table><div><em>Return type: </em>{{undefined}}</div></dd><dt><dfn><code>abort</code></dfn></dt><dd>
          <p>Aborts the current segment and resets the segment parser.</p>

          <ol class="method-algorithm">
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=] then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{MediaSource/readyState}} attribute of the [=parent media source=] is not in the {{ReadyState/""open""}} state then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the [=range removal=] algorithm is running, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then run the following steps:
              <ol>
                <li>Abort the [=buffer append=] algorithm if it is running.</li>
                <li>Set the {{SourceBuffer/updating}} attribute to false.</li>
                <li>[=Queue a task=] to [=fire an event=] named {{abort}} at this <a>SourceBuffer</a> object.</li>
                <li>[=Queue a task=] to [=fire an event=] named {{updateend}} at this <a>SourceBuffer</a> object.</li>
              </ol>
            </li>
            <li>Run the [=reset parser state=] algorithm.</li>
            <li>Set {{SourceBuffer/appendWindowStart}} to the [=presentation start time=].</li>
            <li>Set {{SourceBuffer/appendWindowEnd}} to positive Infinity.</li>
          </ol>
        <div><em>No parameters.</em></div><div><em>Return type: </em>{{undefined}}</div></dd>
        <dt><dfn><code>changeType</code></dfn></dt><dd>
        <p>Changes the MIME type associated with this object. Subsequent {{SourceBuffer/appendBuffer()}} calls will expect the newly appended bytes to conform to the new type.</a>
          <ol class="method-algorithm">
            <li>If |type:DOMString| is an empty string then throw a {{TypeError}} exception and abort these steps.</li>
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=], then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If |type| contains a MIME type that is not supported or contains a MIME type that is not supported with the types specified (currently or previously) of {{SourceBuffer}} objects in the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=], then throw a {{NotSupportedError}} exception and abort these steps.</li>
            <li>
              <p>If the {{MediaSource/readyState}} attribute of the [=parent media source=] is in the {{ReadyState/""ended""}} state then run the following steps:</p>
              <ol>
                <li>Set the {{MediaSource/readyState}} attribute of the [=parent media source=] to {{ReadyState/""open""}}.</li>
                <li>[=Queue a task=] to [=fire an event=] named {{sourceopen}} at the [=parent media source=].</li>
              </ol>
            </li>
            <li>Run the [=reset parser state=] algorithm.</li>
            <li>Update the {{SourceBuffer/[[generate timestamps flag]]}} on this {{SourceBuffer}} object to the value in
              the "Generate Timestamps Flag" column of the byte stream format registry [[MSE-REGISTRY]] entry that is
              associated with |type|.</li>
            <li>
                <dl class="switch">
                  <dt>If the {{SourceBuffer/[[generate timestamps flag]]}} equals true:</dt>
                  <dd>
                  Set the {{SourceBuffer/mode}} attribute on this {{SourceBuffer}} object to {{AppendMode/""sequence""}}, including running the associated steps for that attribute being set.
                  </dd>
                  <dt>Otherwise:</dt>
                  <dd>
                  Keep the previous value of the {{SourceBuffer/mode}} attribute on this {{SourceBuffer}} object, without running any associated steps for that attribute being set.
                  </dd>
                </dl>
            </li>
            <li>Set the {{SourceBuffer/[[pending initialization segment for changeType flag]]}} on this {{SourceBuffer}}
              object to true.
          </ol>
          <table class="parameters">
            <tbody>
              <tr>
                <th>Parameter</th>
                <th>Type</th>
                <th>Nullable</th>
                <th>Optional</th>
                <th>Description</th>
              </tr>
              <tr>
                <td class="prmName">|type|</td>
                <td class="prmType">{{DOMString}}</td>
                <td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td>
                <td class="prmOptFalse"><span role="img" aria-label="False">✘</span></td>
                <td class="prmDesc"></td>
              </tr>
            </tbody>
          </table>
          <div><em>Return type: </em>{{undefined}}</div></dd>
        <dt><dfn><code>remove</code></dfn></dt><dd>
        <p>Removes media for a specific time range.</p>
        <ol class="method-algorithm">
            <li>If this object has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=] then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If {{MediaSource/duration}} equals NaN, then throw a {{TypeError}} exception and abort these steps.</li>
            <li>If |start:double| is negative or greater than {{MediaSource/duration}}, then throw a {{TypeError}} exception and abort these steps.</li>
            <li>If |end:unrestricted double| is less than or equal to |start| or |end| equals NaN, then throw a {{TypeError}} exception and abort these steps.</li>
            <li>
              <p>If the {{MediaSource/readyState}} attribute of the [=parent media source=] is in the {{ReadyState/""ended""}} state then run
                the following steps:</p>
              <ol>
                <li>Set the {{MediaSource/readyState}} attribute of the [=parent media source=] to {{ReadyState/""open""}}</li>
                <li>[=Queue a task=] to [=fire an event=] named {{sourceopen}} at the [=parent media source=].</li>
              </ol>
            </li>
            <li>Run the [=range removal=] algorithm with |start| and |end| as the start and end of the removal range.</li>
       </ol>

      <table class="parameters">
        <tbody>
          <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Nullable</th>
            <th>Optional</th>
            <th>Description</th>
          </tr>
          <tr>
            <td class="prmName">|start|</td>
            <td class="prmType">{{double}}</td>
            <td class="prmNullFalse"><span aria-label="False" role=
            "img">✘</span></td>
            <td class="prmOptFalse"><span aria-label="False" role=
            "img">✘</span></td>
            <td class="prmDesc">The start of the removal range, in seconds measured from [=presentation start time=].</td>
          </tr>
          <tr>
            <td class="prmName">|end|</td>
            <td class="prmType">{{unrestricted double}}</td>
            <td class="prmNullFalse"><span aria-label="False" role=
            "img">✘</span></td>
            <td class="prmOptFalse"><span aria-label="False" role=
            "img">✘</span></td>
            <td class="prmDesc">The end of the removal range, in seconds measured from [=presentation start time=].</td>
          </tr>
        </tbody>
      </table>
        <div><em>Return type: </em>{{undefined}}</div>
      </dd></dl>
      </section>

      <section id="track-buffers">
        <h3>Track Buffers</h3>
        <p>A <dfn id="track-buffer">track buffer</dfn> stores the [=track descriptions=] and [=coded frames=] for an individual
          track. The track buffer is updated as [=initialization segments=] and [=media segments=] are appended to the
          <a>SourceBuffer</a>.</p>

        <p>Each [=track buffer=] has a <dfn id="last-decode-timestamp">last decode timestamp</dfn> variable that stores
          the decode timestamp of the last [=coded frame=] appended in the current [=coded frame group=]. The variable is initially
          unset to indicate that no [=coded frames=] have been appended yet.</p>

        <p>Each [=track buffer=] has a <dfn id="last-frame-duration">last frame duration</dfn> variable that stores
          the [=coded frame duration=] of the last [=coded frame=] appended in the current [=coded frame group=]. The variable is initially
          unset to indicate that no [=coded frames=] have been appended yet.</p>

        <p>Each [=track buffer=] has a <dfn id="highest-end-timestamp">highest end timestamp</dfn> variable that stores
            the highest [=coded frame end timestamp=] across all [=coded frames=] in
            the current [=coded frame group=] that were appended to this track buffer.
            The variable is initially unset to indicate that no [=coded frames=] have been appended yet.</p>

        <p>Each [=track buffer=] has a <dfn id="need-RAP-flag">need random access point flag</dfn> variable that keeps track of whether
          the track buffer is waiting for a [=random access point=] [=coded frame=]. The variable is initially set to true to
          indicate that [=random access point=] [=coded frame=] is needed before anything can be added to the
          [=track buffer=].</p>

        <p>Each [=track buffer=] has a <dfn id="track-buffer-ranges">track buffer ranges</dfn> variable that represents the presentation time ranges occupied by the [=coded frames=] currently stored in the track buffer.</p>

          <p class="note">For track buffer ranges, these presentation time ranges are based on [=presentation timestamps=], frame durations, and potentially coded frame group start times for coded frame groups across track buffers in a muxed <a>SourceBuffer</a>.</p>

          <p>For specification purposes, this information is treated as if it were stored in a <a def-id="normalized-timeranges-object"></a>. Intersected [=track buffer ranges=] are used to report {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}}, and MUST therefore support uninterrupted playback within each range of {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}}.</p>

          <p class="note">These coded frame group start times differ slightly from those mentioned in the [=coded frame processing=] algorithm in that they are the earliest [=presentation timestamp=] across all track buffers following a discontinuity. Discontinuities can occur within the [=coded frame processing=] algorithm or result from the [=coded frame removal=] algorithm, regardless of {{SourceBuffer/mode}}.
          The threshold for determining disjointness of [=track buffer ranges=] is implementation-specific. For example, to reduce unexpected playback stalls, implementations MAY approximate the [=coded frame processing=] algorithm's discontinuity detection logic by coalescing adjacent ranges separated by a gap smaller than 2 times the maximum frame duration buffered so far in this [=track buffer=]. Implementations MAY also use coded frame group start times as range start times across [=track buffers=] in a muxed <a>SourceBuffer</a> to further reduce unexpected playback stalls.</p>
      </section>

      <section id="sourcebuffer-events">
        <h3>Event Summary</h3>
        <table class="old-table">
          <thead>
            <tr>
              <th>Event name</th>
              <th>Interface</th>
              <th>Dispatched when...</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><dfn><code>updatestart</code></dfn></td>
              <td><code>Event</code></td>
              <td>{{SourceBuffer/updating}} transitions from false to true.</td>
            </tr>
            <tr>
              <td><dfn><code>update</code></dfn></td>
              <td><code>Event</code></td>
              <td>The append or remove has successfully completed. {{SourceBuffer/updating}} transitions from true to false.</td>
            </tr>
            <tr>
              <td><dfn><code>updateend</code></dfn></td>
              <td><code>Event</code></td>
              <td>The append or remove has ended.</td>
            </tr>
            <tr>
              <td><dfn><code>error</code></dfn></td>
              <td><code>Event</code></td>
              <td>An error occurred during the append. {{SourceBuffer/updating}} transitions from true to false.</td>
            </tr>
            <tr>
              <td><dfn><code>abort</code></dfn></td>
              <td><code>Event</code></td>
              <td>The append was aborted by an {{SourceBuffer/abort()}} call. {{SourceBuffer/updating}} transitions from true to false.</td>
            </tr>
          </tbody>
        </table>
      </section>

      <section id="sourcebuffer-algorithms">
        <h3>Algorithms</h3>

        <section id="sourcebuffer-segment-parser-loop">
          <h4><dfn>Segment Parser Loop</dfn></h4>
          <p>Each {{SourceBuffer}} object has an <dfn data-dfn-for="SourceBuffer">[[\append state]]</dfn> internal slot
          that keeps track of the high-level segment parsing state. It is initially set to [=WAITING_FOR_SEGMENT=] and
          can transition to the following states as data is appended.</p>
          <table class="old-table">
            <thead>
              <tr>
                <th>Append state name</th>
                <th>Description</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td><dfn id="sourcebuffer-waiting-for-segment"><code>WAITING_FOR_SEGMENT</code></dfn></td>
                <td>Waiting for the start of an [=initialization segment=] or [=media segment=] to be appended.</td>
              </tr>
              <tr>
                <td><dfn id="sourcebuffer-parsing-init-segment"><code>PARSING_INIT_SEGMENT</code></dfn></td>
                <td>Currently parsing an [=initialization segment=].</td>
              </tr>
              <tr>
                <td><dfn id="sourcebuffer-parsing-media-segment"><code>PARSING_MEDIA_SEGMENT</code></dfn></td>
                <td>Currently parsing a [=media segment=].</td>
              </tr>
            </tbody>
          </table>

          <p>Each {{SourceBuffer}} object has an <dfn data-dfn-for="SourceBuffer">[[\input buffer]]</dfn> internal slot
            that is a byte buffer that holds unparsed bytes across {{SourceBuffer/appendBuffer()}} calls. The buffer is
            empty when the {{SourceBuffer}} object is created.</p>

          <p>Each {{SourceBuffer}} object has a <dfn data-dfn-for="SourceBuffer">[[\buffer full flag]]</dfn> internal
            slot that keeps track of whether {{SourceBuffer/appendBuffer()}} is allowed to accept more bytes. It is set
            to false when the {{SourceBuffer}} object is created and gets updated as data is appended and removed.</p>

          <p>Each {{SourceBuffer}} object has a <dfn data-dfn-for="SourceBuffer">[[\group start timestamp]]</dfn>
            internal slot that keeps track of the starting timestamp for a new [=coded frame group=] in the
            {{AppendMode/""sequence""}} mode. It is unset when the SourceBuffer object is created and gets updated when
            the {{SourceBuffer/mode}} attribute equals {{AppendMode/""sequence""}} and the
            {{SourceBuffer/timestampOffset}} attribute is set, or the [=coded frame processing=] algorithm runs.
          </p>

          <p>Each {{SourceBuffer}} object has a <dfn data-dfn-for="SourceBuffer">[[\group end timestamp]]</dfn> internal
            slot that stores the highest [=coded frame end timestamp=] across all [=coded frames=] in the current
            [=coded frame group=]. It is set to 0 when the SourceBuffer object is created and gets updated by the
            [=coded frame processing=] algorithm.
          </p>
          <p class="note">The {{SourceBuffer/[[group end timestamp]]}} stores the highest [=coded frame end timestamp=]
            across all [=track buffers=] in a <a>SourceBuffer</a>. Therefore, care should be taken in setting the
            {{SourceBuffer/mode}} attribute when appending multiplexed segments in which the timestamps are not aligned
            across tracks.
          </p>

          <p>Each {{SourceBuffer}} object has a
            <dfn data-dfn-for="SourceBuffer" data-export="">[[\generate timestamps flag]]</dfn> internal slot that is a
            boolean that keeps track of whether timestamps need to be generated for the [=coded frames=] passed to the
            [=coded frame processing=] algorithm.
            This flag is set by {{MediaSource/addSourceBuffer()}} when the {{SourceBuffer}} object is created and is
            updated by {{SourceBuffer/changeType()}}.
          </p>
          <p>When the segment parser loop algorithm is invoked, run the following steps:</p>

          <ol>
            <li><i>Loop Top:</i> If the {{SourceBuffer/[[input buffer]]}} is empty, then jump to the <i>need more
            data</i> step below.</li>
            <li>If the {{SourceBuffer/[[input buffer]]}} contains bytes that violate the [=SourceBuffer byte stream
              format specification=], then run the [=append error=] algorithm and abort this algorithm.</li>
            <li>Remove any bytes that the [=byte stream format specifications=] say MUST be ignored from the start of
              the {{SourceBuffer/[[input buffer]]}}.</li>
            <li>
              <p>If the {{SourceBuffer/[[append state]]}} equals [=WAITING_FOR_SEGMENT=], then run the following
              steps:</p>
              <ol>
                <li>If the beginning of the {{SourceBuffer/[[input buffer]]}} indicates the start of an [=initialization
                  segment=], set the {{SourceBuffer/[[append state]]}} to [=PARSING_INIT_SEGMENT=].</li>
                <li>If the beginning of the {{SourceBuffer/[[input buffer]]}} indicates the start of a [=media
                  segment=], set {{SourceBuffer/[[append state]]}} to [=PARSING_MEDIA_SEGMENT=].</li>
                <li>Jump to the <i>loop top</i> step above.</li>
              </ol>
            </li>
            <li>
              <p>If the {{SourceBuffer/[[append state]]}} equals [=PARSING_INIT_SEGMENT=], then run the following
              steps:</p>
              <ol>
                <li>If the {{SourceBuffer/[[input buffer]]}} does not contain a complete [=initialization segment=] yet,
                  then jump to the <i>need more data</i> step below.</li>
                <li>Run the [=initialization segment received=] algorithm.</li>
                <li>Remove the [=initialization segment=] bytes from the beginning of the {{SourceBuffer/[[input
                  buffer]]}}.</li>
                <li>Set {{SourceBuffer/[[append state]]}} to [=WAITING_FOR_SEGMENT=].</li>
                <li>Jump to the <i>loop top</i> step above.</li>
              </ol>
            </li>
            <li>
              <p>If the {{SourceBuffer/[[append state]]}} equals [=PARSING_MEDIA_SEGMENT=], then run the following
              steps:</p>
              <ol>
                <li>If the {{SourceBuffer/[[first initialization segment received flag]]}} is false or the
                  {{SourceBuffer/[[pending initialization segment for changeType flag]]}} is true, then run the [=append
                  error=] algorithm and abort this algorithm.</li>
                <li>If the {{SourceBuffer/[[input buffer]]}} contains one or more complete [=coded frames=], then run
                  the [=coded frame processing=] algorithm.
                  <p class="note">
                    The frequency at which the coded frame processing algorithm is run is implementation-specific. The coded frame processing algorithm MAY
                    be called when the input buffer contains the complete media segment or it MAY be called multiple times as complete coded frames are
                    added to the input buffer.
                  </p>
                </li>
                <li>If this {{SourceBuffer}} is full and cannot accept more media data, then set the
                  {{SourceBuffer/[[buffer full flag]]}} to true.</li>
                <li>If the {{SourceBuffer/[[input buffer]]}} does not contain a complete [=media segment=], then jump to
                  the <i>need more data</i> step below.</li>
                <li>Remove the [=media segment=] bytes from the beginning of the {{SourceBuffer/[[input buffer]]}}.</li>
                <li>Set {{SourceBuffer/[[append state]]}} to [=WAITING_FOR_SEGMENT=].</li>
                <li>Jump to the <i>loop top</i> step above.</li>
              </ol>
            </li>
            <li><i>Need more data:</i> Return control to the calling algorithm.</li>
          </ol>
        </section>

        <section id="sourcebuffer-reset-parser-state">
          <h4><dfn>Reset Parser State</dfn></h4>
          <p>When the parser state needs to be reset, run the following steps:</p>
          <ol>
            <li>If the {{SourceBuffer/[[append state]]}} equals [=PARSING_MEDIA_SEGMENT=] and the {{SourceBuffer/[[input
              buffer]]}} contains some complete [=coded frames=], then run the [=coded frame processing=] algorithm
              until all of these complete [=coded frames=] have been processed.</li>
            <li>Unset the [=last decode timestamp=] on all [=track buffers=].</li>
            <li>Unset the [=last frame duration=] on all [=track buffers=].</li>
            <li>Unset the [=highest end timestamp=] on all [=track buffers=].</li>
            <li>Set the [=need random access point flag=] on all [=track buffers=] to true.</li>
            <li>If the {{SourceBuffer/mode}} attribute equals {{AppendMode/""sequence""}}, then set the
              {{SourceBuffer/[[group start timestamp]]}} to the {{SourceBuffer/[[group end timestamp]]}}</li>
            <li>Remove all bytes from the {{SourceBuffer/[[input buffer]]}}.</li>
            <li>Set {{SourceBuffer/[[append state]]}} to [=WAITING_FOR_SEGMENT=].</li>
          </ol>
        </section>

        <section id="sourcebuffer-append-error">
          <h4><dfn data-export="">Append Error</dfn></h4>
          <p>This algorithm is called when an error occurs during an append.
          <ol>
            <li>Run the [=reset parser state=] algorithm.</li>
            <li>Set the {{SourceBuffer/updating}} attribute to false.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{error}} at this <a>SourceBuffer</a> object.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{updateend}} at this <a>SourceBuffer</a> object.</li>
            <li>Run the [=end of stream=] algorithm
              with the |error:EndOfStreamError| parameter set to {{EndOfStreamError/""decode""}}.</li>
          </ol>
        </section>

        <section id="sourcebuffer-prepare-append">
            <h4><dfn>Prepare Append</dfn></h4>
            <p>When an append operation begins, the following steps are run to validate and prepare the <a>SourceBuffer</a>.</p>
            <ol>
            <li>If the <a>SourceBuffer</a> has been removed from the {{MediaSource/sourceBuffers}} attribute of the [=parent media source=] then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>If the {{SourceBuffer/updating}} attribute equals true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>Let |recent element error:boolean| be determined as follows:
              <dl class="switch">
                <dt>If the {{MediaSource}} was constructed in a {{Window}}</dt>
                <dd>Let |recent element error| be true if the {{HTMLMediaElement}}.{{HTMLMediaElement/error}} attribute
                is not null. If that attribute is null, then let |recent element error| be false.</dd>
                <dt>Otherwise</dt>
                <dd>Let |recent element error| be the value resulting from the steps for the {{Window}} case, but run
                on the {{Window}} {{HTMLMediaElement}} on any change to its {{HTMLMediaElement/error}} attribute and
                communicated by using {{HTMLMediaElement/[[port to worker]]}} implicit messages. If such a message has
                not yet been received, then let |recent element error| be false.</dd>
              </dl>
            </li>
            <li>If |recent element error| is true, then throw an {{InvalidStateError}} exception and abort these steps.</li>
            <li>
              <p>If the {{MediaSource/readyState}} attribute of the [=parent media source=] is in the {{ReadyState/""ended""}} state then run the following steps:</p>
              <ol>
                <li>Set the {{MediaSource/readyState}} attribute of the [=parent media source=] to {{ReadyState/""open""}}
                </li>
                <li>
                  [=Queue a task=] to [=fire an event=] named {{sourceopen}} at the [=parent media source=].</li>
              </ol>
            </li>
            <li>Run the [=coded frame eviction=] algorithm.</li>
            <li>
              <p>If the {{SourceBuffer/[[buffer full flag]]}} equals true, then throw a {{QuotaExceededError}} exception
                and abort these steps.</p>
              <p class="note">This is the signal that the implementation was unable to evict enough data to accommodate the append or the append is too big. The web
                application SHOULD use {{SourceBuffer/remove()}} to explicitly free up space and/or reduce the size of the append.</p>
            </li>
            </ol>
        </section>

        <section id="sourcebuffer-buffer-append">
          <h4><dfn>Buffer Append</dfn></h4>
          <p>When {{SourceBuffer/appendBuffer()}} is called, the following steps are run to process the appended data.</p>
          <ol>
            <li>Run the [=segment parser loop=] algorithm.</li>
            <li>If the [=segment parser loop=] algorithm in the previous step was aborted, then abort this algorithm.</li>
            <li>Set the {{SourceBuffer/updating}} attribute to false.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{update}} at this <a>SourceBuffer</a> object.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{updateend}} at this <a>SourceBuffer</a> object.</li>
          </ol>
        </section>

        <section id="sourcebuffer-range-removal">
          <h4><dfn>Range Removal</dfn></h4>
          <p>Follow these steps when a caller needs to initiate a JavaScript visible range removal
            operation that blocks other SourceBuffer updates:</p>
          <ol>
            <li>Let |start:double| equal the starting [=presentation timestamp=] for the removal range, in seconds measured from [=presentation start time=].</li>
            <li>Let |end:unrestricted double| equal the end [=presentation timestamp=] for the removal range, in seconds measured from [=presentation start time=].</li>
            <li>Set the {{SourceBuffer/updating}} attribute to true.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{updatestart}} at this <a>SourceBuffer</a> object.</li>
            <li>Return control to the caller and run the rest of the steps asynchronously.</li>
            <li>Run the [=coded frame removal=] algorithm with |start| and |end| as the start and end of the removal range.</li>
            <li>Set the {{SourceBuffer/updating}} attribute to false.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{update}} at this <a>SourceBuffer</a> object.</li>
            <li>[=Queue a task=] to [=fire an event=] named {{updateend}} at this <a>SourceBuffer</a> object.</li>
          </ol>
        </section>

        <section id="sourcebuffer-init-segment-received">
          <h4><dfn>Initialization Segment Received</dfn></h4>
          <p>The following steps are run when the [=segment parser loop=] successfully parses a complete [=initialization segment=]:</p>
          <p>Each SourceBuffer object has a
          <dfn data-dfn-for="SourceBuffer">[[\first initialization segment received flag]]</dfn> internal slot that
          tracks whether the first [=initialization segment=] has been appended and received by this algorithm.  This
          flag is set to false when the SourceBuffer is created and updated by the algorithm below.</p>
          <p>Each SourceBuffer object has a
          <dfn data-dfn-for="SourceBuffer">[[\pending initialization segment for changeType flag]]</dfn> internal slot
          that tracks whether an [=initialization segment=] is needed since the most recent
          {{SourceBuffer/changeType()}}.  This flag is set to false when the SourceBuffer is created, set to true by
          {{SourceBuffer/changeType()}} and reset to false by the algorithm below.</p>
          <ol>
            <li>Update the {{MediaSource/duration}} attribute if it currently equals NaN:
              <dl class="switch">
                <dt>If the initialization segment contains a duration:</dt>
                <dd>Run the [=duration change=] algorithm with |new duration:unrestricted double| set to the duration in
                the initialization segment.</dd>
                <dt>Otherwise:</dt>
                <dd>Run the [=duration change=] algorithm with |new duration| set to positive Infinity.</dd>
              </dl>
            </li>
            <li>If the [=initialization segment=] has no audio, video, or text tracks, then run the [=append error=] algorithm  and abort these steps.</li>
            <li>If the {{SourceBuffer/[[first initialization segment received flag]]}} is true, then run the following
              steps:
              <ol>
                <li>Verify the following properties. If any of the checks fail then run the [=append error=] algorithm and abort these steps.
                  <ul>
                    <li>The number of audio, video, and text tracks match what was in the first [=initialization segment=].</li>
                    <li>If more than one track for a single type are present (e.g., 2 audio tracks), then the [=Track IDs=] match the ones in the
                      first [=initialization segment=].</li>
                    <li>The codecs for each track are supported by the user agent.
                      <p class="note">User agents MAY consider codecs, that would otherwise be supported, as "not supported" here if the codecs were not
                        specified in |type:DOMString| parameter passed to
                        (a) the most recently successful {{SourceBuffer/changeType()}} on this {{SourceBuffer}} object, or
                        (b) if no successful {{SourceBuffer/changeType()}} has yet occurred on this object, the {{MediaSource/addSourceBuffer()}}
                        that created this {{SourceBuffer}} object.
                        For example, if the most recently successful {{SourceBuffer/changeType()}} was called with <code>'video/webm'</code>
                        or <code>'video/webm; codecs="vp8"'</code>, and a video track containing vp9 appears in the initialization segment,
                        then the user agent MAY use this step to trigger a decode error even if the other two properties'
                        checks, above, pass. Implementations are encouraged to trigger error in such cases only when the codec
                        is indeed not supported or the other two properties' checks fail.
                        Web authors are encouraged to use {{SourceBuffer/changeType()}}, {{MediaSource/addSourceBuffer()}} and
                        {{MediaSource/isTypeSupported()}} with precise codec parameters to more proactively detect user agent
                        support. {{SourceBuffer/changeType()}} is required if the {{SourceBuffer}} object's bytestream format
                        is changing.
                      </p>
                    </li>
                  </ul>
                </li>
                <li>Add the appropriate [=track descriptions=] from this [=initialization segment=] to each of the
                  [=track buffers=].</li>
                <li>Set the [=need random access point flag=] on all track buffers to true.</li>
              </ol>
            </li>
            <li>Let |active track flag:boolean| equal false.</li>
            <li>
              <p>If the {{SourceBuffer/[[first initialization segment received flag]]}} is false, then run the following
              steps:</p>
              <ol>
                <li>If the [=initialization segment=] contains tracks with codecs the user agent does not support, then run the [=append error=] algorithm and abort these steps.
                  <p class="note">User agents MAY consider codecs, that would otherwise be supported, as "not supported" here if the codecs were not
                    specified in |type:DOMString| parameter passed to
                    (a) the most recently successful {{SourceBuffer/changeType()}} on this {{SourceBuffer}} object, or
                    (b) if no successful {{SourceBuffer/changeType()}} has yet occurred on this object, the {{MediaSource/addSourceBuffer()}}
                    that created this {{SourceBuffer}} object.
                    For example, <code>MediaSource.isTypeSupported('video/webm;codecs="vp8,vorbis"')</code> may return true, but if
                    {{MediaSource/addSourceBuffer()}} was called with <code>'video/webm;codecs="vp8"'</code> and a Vorbis track appears in the
                    [=initialization segment=], then the user agent MAY use this step to trigger a decode error.
                    Implementations are encouraged to trigger error in such cases only when the codec is indeed not supported.
                    Web authors are encouraged to use {{SourceBuffer/changeType()}}, {{MediaSource/addSourceBuffer()}} and
                    {{MediaSource/isTypeSupported()}} with precise codec parameters to more proactively detect user agent
                    support. {{SourceBuffer/changeType()}} is required if the {{SourceBuffer}} object's bytestream format
                    is changing.
                  </p>
                </li>
                <li>
                  <p>For each audio track in the [=initialization segment=], run following steps:</p>
                  <ol>
                    <li>Let |audio byte stream track ID| be the
                      [=Track ID=] for the current track being processed.</li>
                    <li>Let |audio language:DOMString| be a BCP 47 language tag for the language
                      specified in the [=initialization segment=] for this track or an empty string if no
                      language info is present.</li>
                    <li>If |audio language| equals the 'und' BCP 47 value, then assign an empty string to |audio language|.</li>
                    <li>Let |audio label:DOMString| be a label specified in the [=initialization segment=] for this track or an empty string if no
                      label info is present.</li>
                    <li>Let |audio kinds:DOMString sequence| be a sequence of kind strings specified in the
                      [=initialization segment=] for this track
                      or a sequence with a single empty string element in it
                      if no kind information is provided.</li>
                    <li>For each value in |audio kinds|, run the following steps:
                      <ol>
                        <li>Let |current audio kind:DOMString| equal the value from |audio kinds|
                          for this iteration of the loop.</li>
                        <li>Let |new audio track:AudioTrack| be a new {{AudioTrack}} object.</li>
                        <li>Generate a unique ID and assign it to the {{AudioTrack/id}} property on
                          |new audio track|.</li>
                        <li>Assign |audio language| to the {{AudioTrack/language}}
                          property on |new audio track|.</li>
                        <li>Assign |audio label| to the {{AudioTrack/label}}
                          property on |new audio track|.</li>
                        <li>Assign |current audio kind| to the {{AudioTrack/kind}}
                          property on |new audio track|.</li>
                        <li>
                          <p>
                            If this {{SourceBuffer}} object's {{SourceBuffer/audioTracks}}.{{AudioTrackList/length}}</a> equals 0, then run
                            the following steps:
                          </p>
                          <ol>
                            <li>Set the {{AudioTrack/enabled}} property on |new audio track| to true.</li>
                            <li>Set |active track flag| to true.</li>
                          </ol>
                        </li>
                        <li>Add |new audio track| to the {{SourceBuffer/audioTracks}} attribute on this <a>SourceBuffer</a> object.
                        <p class="note">
                          This should trigger {{AudioTrackList}} [[HTML]] logic to
                          [=queue a task=] to [=fire an event=] named [=AudioTrackList/addtrack=]
                          using {{TrackEvent}} with the {{TrackEvent/track}} attribute initialized to
                          |new audio track|, at the {{AudioTrackList}} object referenced by the
                          {{SourceBuffer/audioTracks}} attribute on this <a>SourceBuffer</a> object.
                        </p>
                        </li>
                        <li>
                          <dl class="switch">
                            <dt>If the [=parent media source=] was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                            <dd>Post an internal <code>create track mirror</code> message to {{MediaSource/[[port to
                            main]]}} whose implicit handler in {{Window}} runs the following steps:<ol>
                              <li>Let |mirrored audio track:AudioTrack| be a new {{AudioTrack}} object.</li>
                              <li>Assign the same property values to |mirrored audio track| as were determined for
                                |new audio track|.</li>
                              <li>Add |mirrored audio track| to the {{HTMLMediaElement/audioTracks}} attribute
                                on the HTMLMediaElement.</li>
                            </ol></dd>
                            <dt>Otherwise:</dt>
                            <dd>Add |new audio track| to the {{HTMLMediaElement/audioTracks}} attribute on the
                            HTMLMediaElement.</dd>
                          </dl>
                          <p class="note">
                            This should trigger {{AudioTrackList}} [[HTML]] logic to
                            [=queue a task=] to [=fire an event=] named [=AudioTrackList/addtrack=]
                            using {{TrackEvent}} with the {{TrackEvent/track}} attribute initialized to
                            |mirrored audio track| or |new audio track|, at the {{AudioTrackList}} object referenced by
                            the {{HTMLMediaElement/audioTracks}} attribute on the HTMLMediaElement.
                          </p>
                        </li>
                      </ol>
                    </li>
                    <li>Create a new [=track buffer=] to store [=coded frames=] for this track.</li>
                    <li>Add the [=track description=] for this track to the [=track buffer=].</li>
                  </ol>
                </li>
                <li>
                  <p>For each video track in the [=initialization segment=], run following steps:</p>
                  <ol>
                    <li>Let |video byte stream track ID| be the
                      [=Track ID=] for the current track being processed.</li>
                    <li>Let |video language:DOMString| be a BCP 47 language tag for the language
                      specified in the [=initialization segment=] for this track or an empty string if no
                      language info is present.</li>
                    <li>If |video language| equals the 'und' BCP 47 value, then assign an empty string to |video language|.</li>
                    <li>Let |video label:DOMString| be a label specified in the [=initialization segment=] for this track or an empty string if no
                      label info is present.</li>
                    <li>Let |video kinds:DOMString sequence| be a sequence of kind strings specified in the
                      [=initialization segment=] for this track
                      or a sequence with a single empty string element in it
                      if no kind information is provided.</li>
                    <li>For each value in |video kinds|, run the following steps:
                      <ol>
                        <li>Let |current video kind:DOMString| equal the value from |video kinds|
                          for this iteration of the loop.</li>
                        <li>Let |new video track:VideoTrack| be a new {{VideoTrack}} object.</li>
                        <li>Generate a unique ID and assign it to the {{VideoTrack/id}} property on
                          |new video track|.</li>
                        <li>Assign |video language| to the {{VideoTrack/language}}
                          property on |new video track|.</li>
                        <li>Assign |video label| to the {{VideoTrack/label}}
                          property on |new video track|.</li>
                        <li>Assign |current video kind| to the {{VideoTrack/kind}}
                          property on |new video track|.</li>
                        <li>
                          <p>
                            If this {{SourceBuffer}} object's {{SourceBuffer/videoTracks}}.{{VideoTrackList/length}} equals 0, then run
                            the following steps:
                          </p>
                          <ol>
                            <li>Set the {{VideoTrack/selected}} property on |new video track| to true.</li>
                            <li>Set |active track flag| to true.</li>
                          </ol>
                        </li>
                        <li>Add |new video track| to the {{SourceBuffer/videoTracks}} attribute on this <a>SourceBuffer</a> object.
                        <p class="note">
                          This should trigger {{VideoTrackList}} [[HTML]] logic to
                          [=queue a task=] to [=fire an event=] named [=VideoTrackList/addtrack=]
                          using {{TrackEvent}} with the {{TrackEvent/track}} attribute initialized to
                          |new video track|, at the {{VideoTrackList}} object referenced by the
                          {{SourceBuffer/videoTracks}} attribute on this <a>SourceBuffer</a> object.
                        </p>
                        </li>
                        <li>
                          <dl class="switch">
                            <dt>If the [=parent media source=] was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                            <dd>Post an internal <code>create track mirror</code> message to {{MediaSource/[[port to
                            main]]}} whose implicit handler in {{Window}} runs the following steps:<ol>
                              <li>Let |mirrored video track:VideoTrack| be a new {{VideoTrack}} object.</li>
                              <li>Assign the same property values to |mirrored video track| as were determined for
                                |new video track|.</li>
                              <li>Add |mirrored video track| to the {{HTMLMediaElement/videoTracks}} attribute
                                on the HTMLMediaElement.</li>
                            </ol></dd>
                            <dt>Otherwise:</dt>
                            <dd>Add |new video track| to the {{HTMLMediaElement/videoTracks}} attribute on the
                            HTMLMediaElement.</dd>
                          </dl>
                          <p class="note">
                            This should trigger {{VideoTrackList}} [[HTML]] logic to
                            [=queue a task=] to [=fire an event=] named [=VideoTrackList/addtrack=]
                            using {{TrackEvent}} with the {{TrackEvent/track}} attribute initialized to
                            |mirrored video track| or |new video track|, at the {{VideoTrackList}} object referenced by
                            the {{HTMLMediaElement/videoTracks}} attribute on the HTMLMediaElement.
                          </p>
                        </li>
                      </ol>
                    </li>
                    <li>Create a new [=track buffer=] to store [=coded frames=] for this track.</li>
                    <li>Add the [=track description=] for this track to the [=track buffer=].</li>
                  </ol>
                </li>
                <li>
                  <p>For each text track in the [=initialization segment=], run following steps:</p>
                  <ol>
                    <li>Let |text byte stream track ID| be the
                      [=Track ID=] for the current track being processed.</li>
                    <li>Let |text language:DOMString| be a BCP 47 language tag for the language
                      specified in the [=initialization segment=] for this track or an empty string if no
                      language info is present.</li>
                    <li>If |text language| equals the 'und' BCP 47 value, then assign an empty string to |text language|.</li>
                    <li>Let |text label:DOMString| be a label specified in the [=initialization segment=] for this track or an empty string if no
                      label info is present.</li>
                    <li>Let |text kinds:DOMString sequence| be a sequence of kind strings specified in the
                      [=initialization segment=] for this track
                      or a sequence with a single empty string element in it
                      if no kind information is provided.</li>
                    <li>For each value in |text kinds|, run the following steps:
                      <ol>
                        <li>Let |current text kind:DOMString| equal the value from |text kinds|
                          for this iteration of the loop.</li>
                        <li>Let |new text track:TextTrack| be a new {{TextTrack}} object.</li>
                        <li>Generate a unique ID and assign it to the {{TextTrack/id}} property on
                          |new text track|.</li>
                        <li>Assign |text language| to the {{TextTrack/language}}
                          property on |new text track|.</li>
                        <li>Assign |text label| to the {{TextTrack/label}}
                          property on |new text track|.</li>
                        <li>Assign |current text kind| to the {{TextTrack/kind}}
                          property on |new text track|.</li>
                        <li>Populate the remaining properties on |new text track| with the
                          appropriate information from the [=initialization segment=].</li>
                        <li>If the {{TextTrack/mode}} property on |new text track| equals
                          <a def-id="texttrackmode-showing"></a> or <a def-id="texttrackmode-hidden"></a>, then set
                          |active track flag| to true.
                        </li>
                        <li>Add |new text track| to the {{SourceBuffer/textTracks}} attribute on this <a>SourceBuffer</a> object.
                        <p class="note">
                          This should trigger {{TextTrackList}} [[HTML]] logic to
                          [=queue a task=] to [=fire an event=] named [=TextTrackList/addtrack=]
                          using {{TrackEvent}} with the {{TrackEvent/track}} attribute initialized to
                          |new text track|, at the {{TextTrackList}} object referenced by the
                          {{SourceBuffer/textTracks}} attribute on this <a>SourceBuffer</a> object.
                        </p>
                        </li>
                        <li>
                          <dl class="switch">
                            <dt>If the [=parent media source=] was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                            <dd>Post an internal <code>create track mirror</code> message to {{MediaSource/[[port to
                            main]]}} whose implicit handler in {{Window}} runs the following steps:<ol>
                              <li>Let |mirrored text track:TextTrack| be a new {{TextTrack}} object.</li>
                              <li>Assign the same property values to |mirrored text track| as were determined for
                                |new text track|.</li>
                              <li>Add |mirrored text track| to the {{HTMLMediaElement/textTracks}} attribute
                                on the HTMLMediaElement.</li>
                            </ol></dd>
                            <dt>Otherwise:</dt>
                            <dd>Add |new text track| to the {{HTMLMediaElement/textTracks}} attribute on the
                            HTMLMediaElement.</dd>
                          </dl>
                          <p class="note">
                            This should trigger {{TextTrackList}} [[HTML]] logic to
                            [=queue a task=] to [=fire an event=] named [=TextTrackList/addtrack=]
                            using {{TrackEvent}} with the {{TrackEvent/track}} attribute initialized to
                            |mirrored text track| or |new text track|, at the {{TextTrackList}} object referenced by the
                            {{HTMLMediaElement/textTracks}} attribute on the HTMLMediaElement.
                          </p>
                        </li>
                      </ol>
                    </li>
                    <li>Create a new [=track buffer=] to store [=coded frames=] for this track.</li>
                    <li>Add the [=track description=] for this track to the [=track buffer=].</li>
                  </ol>
                </li>
                <li>If |active track flag| equals true, then run the following steps:
                  <ol>
                    <li>Add this <a>SourceBuffer</a> to {{MediaSource/activeSourceBuffers}}.</li>
                    <li>[=Queue a task=] to [=fire an event=] named {{addsourcebuffer}} at {{MediaSource/activeSourceBuffers}}</li>
                  </ol>
                </li>
                <li>Set {{SourceBuffer/[[first initialization segment received flag]]}} to true.</li>
              </ol>
            </li>
            <li>Set {{SourceBuffer/[[pending initialization segment for changeType flag]]}} to false.</li>
            <li>If the |active track flag| equals true, then run the following steps:
              <dl class="switch">
                <dt>If the [=parent media source=] was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                <dd>Post an internal <code>active track added</code> message to {{MediaSource/[[port to main]]}} whose
                implicit handler in {{Window}} runs the following step:
                <ol>
                  <li>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is greater than
                    {{HTMLMediaElement/HAVE_CURRENT_DATA}}, then set the
                    {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to
                    {{HTMLMediaElement/HAVE_METADATA}}.
                  </li>
                </ol></dd>
                <dt>Otherwise:</dt>
                <dd>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is greater than
                {{HTMLMediaElement/HAVE_CURRENT_DATA}}, then set the
                {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to
                {{HTMLMediaElement/HAVE_METADATA}}.</dd>
              </dl>
              <p class="note">
                Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}}
                changes may trigger events on the HTMLMediaElement.
              </p>
            </li>
            <li>If each object in {{MediaSource/sourceBuffers}} of the [=parent media source=] has
              {{SourceBuffer/[[first initialization segment received flag]]}} equal to true, then run the following
              steps:
              <dl class="switch">
                <dt>If the [=parent media source=] was constructed in a {{DedicatedWorkerGlobalScope}}:</dt>
                <dd>Post an internal <code>sourcebuffers ready</code> message to {{MediaSource/[[port to main]]}} whose
                implicit handler in {{Window}} runs the following step:
                <ol>
                  <li>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is
                    {{HTMLMediaElement/HAVE_NOTHING}}, then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}}
                    attribute to {{HTMLMediaElement/HAVE_METADATA}}.
                  </li>
                </ol><dd>
                <dt>Otherwise:</dt>
                <dd>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is
                {{HTMLMediaElement/HAVE_NOTHING}}, then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}}
                attribute to {{HTMLMediaElement/HAVE_METADATA}}.</dd>
              </dl>
              <p class="note">
                Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}}
                changes may trigger events on the HTMLMediaElement. If transition from {{HTMLMediaElement/HAVE_NOTHING}}
                to {{HTMLMediaElement/HAVE_METADATA}} occurs, it should trigger HTMLMediaElement logic to [=queue a
                task=] to [=fire an event=] named [=HTMLMediaElement/loadedmetadata=] at the media element.
              </p>
            </li>
          </ol>
        </section>

        <section id="sourcebuffer-coded-frame-processing">
          <h4><dfn data-export="">Coded Frame Processing</dfn></h4>
          <p>When complete [=coded frames=] have been parsed by the [=segment parser loop=] then the following steps are run:</p>
          <ol>
            <li>
              <p>For each [=coded frame=] in the [=media segment=] run the following steps:</p>
              <ol>
                <li><i>Loop Top: </i><dl class="switch">
                    <dt>If {{SourceBuffer/[[generate timestamps flag]]}} equals true:</dt>
                    <dd>
                      <ol>
                        <li>Let |presentation timestamp:double| equal 0.</li>
                        <li>Let |decode timestamp:double| equal 0.</li>
                      </ol>
                    </dd>
                    <dt>Otherwise:</dt>
                    <dd>
                      <ol>
                        <li>Let |presentation timestamp| be a double precision floating point representation of the coded frame's [=presentation timestamp=] in seconds.
                          <p class="note">Special processing may be needed to determine the presentation and decode timestamps for timed text frames since this information may not be explicitly
                            present in the underlying format or may be dependent on the order of the frames. Some metadata text tracks, like MPEG2-TS PSI data, may only have implied timestamps.
                            Format specific rules for these situations SHOULD be in the [=byte stream format specifications=] or in separate extension specifications.</p>
                        </li>
                        <li>Let |decode timestamp| be a double precision floating point representation of the coded frame's decode timestamp in seconds.
                          <p class="note">Implementations don't have to internally store timestamps in a double precision floating point representation. This
                            representation is used here because it is the representation for timestamps in the HTML spec. The intention here is to make the
                            behavior clear without adding unnecessary complexity to the algorithm to deal with the fact that adding a timestampOffset may
                            cause a timestamp rollover in the underlying timestamp representation used by the byte stream format. Implementations can use any
                            internal timestamp representation they wish, but the addition of timestampOffset SHOULD behave in a similar manner to what would happen
                            if a double precision floating point representation was used.
                          </p>
                        </li>
                    </ol>
                    </dd>
                  </dl>
                </li>
                <li>Let |frame duration:double| be a double precision floating point representation of the [=coded frame duration|coded frame's duration=] in seconds.</li>
                <li>If {{SourceBuffer/mode}} equals {{AppendMode/""sequence""}} and {{SourceBuffer/[[group start
                  timestamp]]}} is set, then run the following steps:
                  <ol>
                    <li>Set {{SourceBuffer/timestampOffset}} equal to {{SourceBuffer/[[group start timestamp]]}} minus
                        |presentation timestamp|.</li>
                    <li>Set {{SourceBuffer/[[group end timestamp]]}} equal to {{SourceBuffer/[[group start
                      timestamp]]}}.</li>
                    <li>Set the [=need random access point flag=] on all [=track buffers=] to true.</li>
                    <li>Unset {{SourceBuffer/[[group start timestamp]]}}.</li>
                  </ol>
                </li>
                <li>
                  <p>If {{SourceBuffer/timestampOffset}} is not 0, then run the following steps:</p>
                  <ol>
                    <li>Add {{SourceBuffer/timestampOffset}} to the |presentation timestamp|.</li>
                    <li>Add {{SourceBuffer/timestampOffset}} to the |decode timestamp|.</li>
                  </ol>
                </li>
                <li>Let |track buffer| equal the [=track buffer=] that the coded frame will be added to.</li>
                <li>
                  <dl class="switch">
                    <dt>If [=last decode timestamp=] for |track buffer| is set and |decode timestamp| is less than
                      [=last decode timestamp=]:</dt>
                    <dd>OR</dd>
                    <dt>If [=last decode timestamp=] for |track buffer| is set and the difference between |decode timestamp| and [=last decode timestamp=]
                      is greater than 2 times [=last frame duration=]:</dt>
                    <dd>
                      <ol>
                        <li>
                          <dl class="switch">
                            <dt>If {{SourceBuffer/mode}} equals {{AppendMode/""segments""}}:</dt>
                            <dd>Set {{SourceBuffer/[[group end timestamp]]}} to |presentation timestamp|.</dd>
                            <dt>If {{SourceBuffer/mode}} equals {{AppendMode/""sequence""}}:</dt>
                            <dd>Set {{SourceBuffer/[[group start timestamp]]}} equal to the {{SourceBuffer/[[group end
                              timestamp]]}}.</dd>
                          </dl>
                        </li>
                        <li>Unset the [=last decode timestamp=] on all [=track buffers=].</li>
                        <li>Unset the [=last frame duration=] on all [=track buffers=].</li>
                        <li>Unset the [=highest end timestamp=] on all [=track buffers=].</li>
                        <li>Set the [=need random access point flag=] on all [=track buffers=] to true.</li>
                        <li>Jump to the <i>Loop Top</i> step above to restart processing of the current [=coded frame=].</li>
                      </ol>
                    </dd>
                    <dt>Otherwise:</dt>
                    <dd>Continue.</dd>
                  </dl>
                </li>
                <li>Let |frame end timestamp:double| equal the sum of |presentation timestamp| and |frame duration|.</li>
                <li>If |presentation timestamp| is less than {{SourceBuffer/appendWindowStart}}, then set the [=need random access point flag=] to true, drop the
                  coded frame, and jump to the top of the loop to start processing the next coded frame.
                  <p class="note">Some implementations MAY choose to collect some of these coded frames with |presentation timestamp| less than {{SourceBuffer/appendWindowStart}} and use them
                    to generate a splice at the first coded frame that has a [=presentation timestamp=] greater than or equal to {{SourceBuffer/appendWindowStart}} even if
                    that frame is not a [=random access point=]. Supporting this requires multiple decoders or faster than real-time decoding so for now
                    this behavior will not be a normative requirement.
                  </p>
                </li>
                <li>If |frame end timestamp| is greater than {{SourceBuffer/appendWindowEnd}}, then set the [=need random access point flag=] to true, drop the
                  coded frame, and jump to the top of the loop to start processing the next coded frame.
                  <p class="note">Some implementations MAY choose to collect coded frames with |presentation timestamp| less than {{SourceBuffer/appendWindowEnd}} and |frame end timestamp| greater than {{SourceBuffer/appendWindowEnd}} and use them
                  to generate a splice across the portion of the collected coded frames within the append window at time of collection, and the beginning portion of later processed frames which only partially overlap the end of the collected coded frames.
                    Supporting this requires multiple decoders or faster than real-time decoding so for now
                    this behavior will not be a normative requirement.
                    In conjunction with collecting coded frames that span {{SourceBuffer/appendWindowStart}}, implementations MAY thus support gapless audio splicing.
                  </p>
                </li>
                <li>If the [=need random access point flag=] on |track buffer| equals true, then run the following steps:
                  <ol>
                    <li>If the coded frame is not a [=random access point=], then drop the coded frame and jump to the top of the loop to start
                      processing the next coded frame.</li>
                    <li>Set the [=need random access point flag=] on |track buffer| to false.</li>
                  </ol>
                </li>
                <li>Let |spliced audio frame| be an unset variable for holding audio splice information</li>
                <li>Let |spliced timed text frame| be an unset variable for holding timed text splice information</li>
                <li>If [=last decode timestamp=] for |track buffer| is unset and |presentation timestamp| falls within the [=presentation interval=] of a [=coded frame=] in |track buffer|, then run the following steps:
                  <ol>
                    <li>Let |overlapped frame| be the [=coded frame=] in |track buffer| that matches the condition above.</li>
                    <li>
                      <dl class="switch">
                        <dt>If |track buffer| contains audio [=coded frames=]:</dt>
                        <dd>Run the [=audio splice frame=] algorithm and if a splice frame is returned, assign it to |spliced audio frame|.</dd>
                        <dt>If |track buffer| contains video [=coded frames=]:</dt>
                        <dd>
                          <ol>
                            <li>Let |remove window timestamp:double| equal the |overlapped frame| [=presentation timestamp=] plus 1 microsecond.</li>
                            <li>If the |presentation timestamp| is less than the |remove window timestamp|, then remove |overlapped frame| from |track buffer|.
                              <p class="note">
                                This is to compensate for minor errors in frame timestamp computations that can appear when converting back and forth between double precision
                                floating point numbers and rationals. This tolerance allows a frame to replace an existing one as long as it is within 1 microsecond of the existing
                                frame's start time. Frames that come slightly before an existing frame are handled by the removal step below.
                              </p>
                            </li>
                          </ol>
                        </dd>
                        <dt>If |track buffer| contains timed text [=coded frames=]:</dt>
                        <dd>Run the [=text splice frame=] algorithm and if a splice frame is returned, assign it to |spliced timed text frame|.</dd>
                      </dl>
                    </li>
                  </ol>
                </li>
                <li>Remove existing coded frames in |track buffer|:
                  <dl class="switch">
                    <dt>If [=highest end timestamp=] for |track buffer| is not set:</dt>
                    <dd>Remove all [=coded frames=] from |track buffer| that have a [=presentation timestamp=] greater than or equal to
                      |presentation timestamp| and less than |frame end timestamp|.</dd>
                    <dt>If [=highest end timestamp=] for |track buffer| is set and less than or equal to |presentation timestamp|:</dt>
                    <dd>Remove all [=coded frames=] from |track buffer| that have a [=presentation timestamp=] greater than
                      or equal to [=highest end timestamp=] and less than |frame end timestamp|.</dd>
                  </dl>
                </li>
                <li>Remove all possible decoding dependencies on the [=coded frames=] removed in the previous two steps
                  by removing all [=coded frames=] from |track buffer| between those frames removed in the previous two steps and the next
                  [=random access point=] after those removed frames.
                  <p class="note">Removing all [=coded frames=] until the next [=random access point=] is a conservative
                    estimate of the decoding dependencies since it assumes all frames between the removed frames and the next random access point
                    depended on the frames that were removed.
                  </p>
                </li>
                <li>
                  <dl class="switch">
                    <dt>If |spliced audio frame| is set:</dt>
                    <dd>Add |spliced audio frame| to the |track buffer|.</dd>
                    <dt>If |spliced timed text frame| is set:</dt>
                    <dd>Add |spliced timed text frame| to the |track buffer|.</dd>
                    <dt>Otherwise:</dt>
                    <dd>Add the [=coded frame=] with the |presentation timestamp|, |decode timestamp|, and |frame duration| to the
                      |track buffer|.</dd>
                  </dl>
                </li><li>Set [=last decode timestamp=] for |track buffer| to |decode timestamp|.</li>
                <li>Set [=last frame duration=] for |track buffer| to |frame duration|.</li>
                <li>If [=highest end timestamp=] for |track buffer| is unset or |frame end timestamp| is greater
                  than [=highest end timestamp=], then set [=highest end timestamp=] for |track buffer|
                  to |frame end timestamp|.
                  <p class="note">The greater than check is needed because bidirectional prediction between coded frames can cause
                    |presentation timestamp| to not be monotonically increasing even though the decode timestamps are monotonically increasing.</p>
                </li>
                <li>If |frame end timestamp| is greater than {{SourceBuffer/[[group end timestamp]]}}, then set
                  {{SourceBuffer/[[group end timestamp]]}} equal to |frame end timestamp|.</li>
                <li>If {{SourceBuffer/[[generate timestamps flag]]}} equals true, then set
                  {{SourceBuffer/timestampOffset}} equal to |frame end timestamp|.</li>
              </ol>
            </li>
            <li>
              <p>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is {{HTMLMediaElement/HAVE_METADATA}} and the new [=coded frames=] cause {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} to have a {{TimeRanges}} for the current playback position, then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_CURRENT_DATA}}.</p>
              <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
            </li>
            <li>
              <p>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is {{HTMLMediaElement/HAVE_CURRENT_DATA}} and the new [=coded frames=] cause {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} to have a {{TimeRanges}} that includes the current playback position and some time beyond the current playback position, then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_FUTURE_DATA}}.</p>
              <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
            </li>
            <li>
              <p>If the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute is {{HTMLMediaElement/HAVE_FUTURE_DATA}} and the new [=coded frames=] cause {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} to have a {{TimeRanges}} that includes the current playback position and [=enough data to ensure uninterrupted playback=], then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_ENOUGH_DATA}}.</p>
              <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
            </li>
            <li>If the [=media segment=] contains data beyond the current {{MediaSource/duration}}, then run the
              [=duration change=] algorithm with |new duration:unrestricted double| set to the maximum of the current
              duration and the {{SourceBuffer/[[group end timestamp]]}}.</li>
          </ol>
        </section>

        <section id="sourcebuffer-coded-frame-removal">
          <h4><dfn>Coded Frame Removal</dfn></h4>
          <p>Follow these steps when [=coded frames=] for a specific time range need to be removed from the SourceBuffer:</p>
          <ol>
            <li>Let |start:double| be the starting [=presentation timestamp=] for the removal range.</li>
            <li>Let |end:unrestricted double| be the end [=presentation timestamp=] for the removal range. </li>
            <li><p>For each [=track buffer=] in this {{SourceBuffer}}, run the following steps:</p>
              <ol>
                <li>Let |remove end timestamp:unrestricted double| be the current value of {{MediaSource/duration}}</li>
                <li>
                  <p>If this [=track buffer=] has a [=random access point=] timestamp that is greater than or equal to
                    |end|, then update |remove end timestamp| to that random access point timestamp.</p>
                  <p class="note">Random access point timestamps can be different across tracks because the dependencies between [=coded frames=] within a
                    track are usually different than the dependencies in another track.</p>
                </li>
                <li>Remove all media data, from this [=track buffer=], that contain starting timestamps greater than or equal to |start| and less than the |remove end timestamp|.
                <ol>
                  <li><p>For each removed frame, if the frame has a [=decode timestamp=] equal to the [=last decode timestamp=] for the frame's track, run the following steps:</p>
                    <dl class="switch">
                      <dt>If {{SourceBuffer/mode}} equals {{AppendMode/""segments""}}:</dt>
                      <dd>Set {{SourceBuffer/[[group end timestamp]]}} to [=presentation timestamp=].</dd>
                      <dt>If {{SourceBuffer/mode}} equals {{AppendMode/""sequence""}}:</dt>
                      <dd>Set {{SourceBuffer/[[group start timestamp]]}} equal to the {{SourceBuffer/[[group end
                        timestamp]]}}.</dd>
                    </dl>
                  </li>
                  <li>Unset the [=last decode timestamp=] on all [=track buffers=].</li>
                  <li>Unset the [=last frame duration=] on all [=track buffers=].</li>
                  <li>Unset the [=highest end timestamp=] on all [=track buffers=].</li>
                  <li>Set the [=need random access point flag=] on all [=track buffers=] to true.</li>
                </ol>
                </li>
                <li>Remove all possible decoding dependencies on the [=coded frames=] removed in the previous step
                  by removing all [=coded frames=] from this [=track buffer=] between those frames removed in the previous step and the next
                  [=random access point=] after those removed frames.
                  <p class="note">Removing all [=coded frames=] until the next [=random access point=] is a conservative
                    estimate of the decoding dependencies since it assumes all frames between the removed frames and the next random access point
                    depended on the frames that were removed.
                  </p>
                </li>
                <li>
                  <p>If this object is in {{MediaSource/activeSourceBuffers}}, the <a def-id="current-playback-position"></a> is greater than or equal to
                    |start| and less than the |remove end timestamp|, and {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} is greater than
                    {{HTMLMediaElement/HAVE_METADATA}}, then set the {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} attribute to {{HTMLMediaElement/HAVE_METADATA}} and stall playback.</p>
                  <p class="note">Per <a def-id="ready-states"></a> [[HTML]] logic, {{HTMLMediaElement}}.{{HTMLMediaElement/readyState}} changes may trigger events on the HTMLMediaElement.</p>
                  <p class="note">This transition occurs because media data for the current position has been removed. Playback cannot progress until media for the
                    <a def-id="current-playback-position"></a> is appended or the <a href="#active-source-buffer-changes">selected/enabled tracks change</a>.</p>
                </li>
              </ol>
            </li>
            <li>If the {{SourceBuffer/[[buffer full flag]]}} equals true and this object is ready to accept more bytes,
              then set the {{SourceBuffer/[[buffer full flag]]}} to false.</li>
          </ol>
        </section>

        <section id="sourcebuffer-coded-frame-eviction">
          <h4><dfn>Coded Frame Eviction</dfn></h4>
          <p>This algorithm is run to free up space in this {{SourceBuffer}} when new data is appended.</p>
          <ol>
            <li>Let |new data:BufferSource| equal the data that is about to be appended to this SourceBuffer.
              <div class="issue" data-number="289">
                <p>Need to recognize step here that implementations MAY decide to set {{SourceBuffer/[[buffer full
                flag]]}} true here if it predicts that processing |new data| in addition to any existing bytes in
                {{SourceBuffer/[[input buffer]]}} would exceed the capacity of the {{SourceBuffer}}. Such a step enables
                more proactive push-back from implementations before accepting |new data| which would overflow
                resources, for example. In practice, at least one implementation already does this.</p>
              </div>
            </li>
            <li>If the {{SourceBuffer/[[buffer full flag]]}} equals false, then abort these steps.</li>
            <li>Let |removal ranges:normalized TimeRanges| equal a list of presentation time ranges that can be evicted from the presentation to make room for the
              |new data|.
              <p class="note">Implementations MAY use different methods for selecting |removal ranges| so web applications SHOULD NOT depend on a
                specific behavior. The web application can use the {{SourceBuffer/buffered}} attribute to observe whether portions of the buffered data have been evicted.
              </p>
            </li>
            <li>For each range in |removal ranges|, run the [=coded frame removal=] algorithm with |start:double| and |end:unrestricted double| equal to
              the removal range start and end timestamp respectively.</li>
          </ol>
        </section>

        <section id="sourcebuffer-audio-splice-frame-algorithm">
          <h4><dfn>Audio Splice Frame</dfn></h4>
          <p>Follow these steps when the [=coded frame processing=] algorithm needs to generate a splice frame for two overlapping audio
            [=coded frames=]:</p>
          <ol>
            <li>Let |track buffer| be the [=track buffer=] that will contain the splice.</li>
            <li>Let |new coded frame| be the new [=coded frame=], that is being added to |track buffer|, which triggered the need for a splice.</li>
            <li>Let |presentation timestamp:double| be the [=presentation timestamp=] for |new coded frame|.</li>
            <li>Let |decode timestamp:double| be the decode timestamp for |new coded frame|.</li>
            <li>Let |frame duration:double| be the [=coded frame duration=] of |new coded frame|.</li>
            <li>Let |overlapped frame| be the [=coded frame=] in |track buffer| with a [=presentation interval=] that contains |presentation timestamp|.
            </li>
            <li>Update |presentation timestamp| and |decode timestamp| to the nearest audio sample timestamp based on sample rate of the
              audio in |overlapped frame|. If a timestamp is equidistant from both audio sample timestamps, then use the higher timestamp (e.g.,
              <code>floor(x * sample_rate + 0.5) / sample_rate</code>).
              <div class="note">
                <p>For example, given the following values:</p>
                <ul>
                  <li>The [=presentation timestamp=] of |overlapped frame| equals 10.</li>
                  <li>The sample rate of |overlapped frame| equals 8000 Hz</li>
                  <li>|presentation timestamp| equals 10.01255</li>
                  <li>|decode timestamp| equals 10.01255</li>
                </ul>
                <p>|presentation timestamp| and |decode timestamp| are updated to 10.0125 since 10.01255 is closer to
                10 + 100/8000 (10.0125) than 10 + 101/8000 (10.012625)</p>
              </div>
            </li>
            <li>If the user agent does not support crossfading then run the following steps:
              <ol>
                <li>Remove |overlapped frame| from |track buffer|.</li>
                <li>Add a silence frame to |track buffer| with the following properties:
                  <ul>
                    <li>The [=presentation timestamp=] set to the |overlapped frame| [=presentation timestamp=].</li>
                    <li>The [=decode timestamp=] set to the |overlapped frame| [=decode timestamp=].</li>
                    <li>The [=coded frame duration=] set to difference between |presentation timestamp| and the |overlapped frame| [=presentation timestamp=].</li>
                  </ul>
                  <p class="note">
                    Some implementations MAY apply fades to/from silence to coded frames on either side of the inserted silence to make the transition less
                    jarring.
                  </p>
                </li>
                <li>Return to caller without providing a splice frame.
                  <p class="note">
                    This is intended to allow |new coded frame| to be added to the |track buffer| as if
                    |overlapped frame| had not been in the |track buffer| to begin with.
                  </p>
                </li>
              </ol>
            </li>
            <li>Let |frame end timestamp:double| equal the sum of |presentation timestamp| and |frame duration|.</li>
            <li>Let |splice end timestamp:double| equal the sum of |presentation timestamp| and the splice duration of 5 milliseconds.</li>
            <li>Let |fade out coded frames| equal |overlapped frame| as well as any additional frames in |track buffer| that
              have a [=presentation timestamp=] greater than |presentation timestamp| and less than |splice end timestamp|.</li>
            <li>Remove all the frames included in |fade out coded frames| from |track buffer|.
            </li><li>Return a splice frame with the following properties:
              <ul>
                <li>The [=presentation timestamp=] set to the |overlapped frame| [=presentation timestamp=].</li>
                <li>The [=decode timestamp=] set to the |overlapped frame| [=decode timestamp=].</li>
                <li>The [=coded frame duration=] set to difference between |frame end timestamp| and the |overlapped frame| [=presentation timestamp=].</li>
                <li>The fade out coded frames equals |fade out coded frames|.</li>
                <li>The fade in coded frame equals |new coded frame|.
                  <p class="note">If the |new coded frame| is less than 5 milliseconds in duration, then coded frames that are appended after the
                    |new coded frame| will be needed to properly render the splice.</p>
                </li>
                <li>The splice timestamp equals |presentation timestamp|.</li>
              </ul>
              <p class="note">See the [=audio splice rendering=] algorithm for details on how this splice frame is rendered.</p>
            </li>
          </ol>
        </section>
        <section id="sourcebuffer-audio-splice-rendering-algorithm">
          <h4><dfn>Audio Splice Rendering</dfn></h4>
          <p>The following steps are run when a spliced frame, generated by the [=audio splice frame=] algorithm, needs to be rendered by the
            media element:</p>
          <ol>
            <li>Let |fade out coded frames| be the [=coded frames=] that are faded out during the splice.</li>
            <li>Let |fade in coded frames| be the [=coded frames=] that are faded in during the splice.</li>
            <li>Let |presentation timestamp:double| be the [=presentation timestamp=] of the first coded frame in |fade out coded frames|.</li>
            <li>Let |end timestamp:double| be the sum of the [=presentation timestamp=] and the [=coded frame duration=] of the last frame in |fade in coded frames|.</li>
            <li>Let |splice timestamp:double| be the [=presentation timestamp=] where the splice starts. This corresponds with the [=presentation timestamp=] of the first frame in
              |fade in coded frames|.</li>
            <li>Let |splice end timestamp:double| equal |splice timestamp| plus five milliseconds.</li>
            <li>Let |fade out samples| be the samples generated by decoding |fade out coded frames|.</li>
            <li>Trim |fade out samples| so that it only contains samples between |presentation timestamp| and |splice end timestamp|.</li>
            <li>Let |fade in samples| be the samples generated by decoding |fade in coded frames|.</li>
            <li>If |fade out samples| and |fade in samples| do not have a common sample rate and channel layout, then convert
              |fade out samples| and |fade in samples| to a common sample rate and channel layout.</li>
            <li>Let |output samples| be a buffer to hold the output samples.</li>
            <li>Apply a linear gain fade out with a starting gain of 1 and an ending gain of 0 to the samples between
              |splice timestamp| and |splice end timestamp| in |fade out samples|.</li>
            <li>Apply a linear gain fade in with a starting gain of 0 and an ending gain of 1 to the samples between |splice timestamp| and
              |splice end timestamp| in |fade in samples|.</li>
            <li>Copy samples between |presentation timestamp| to |splice timestamp| from |fade out samples| into |output samples|.</li>
            <li>For each sample between |splice timestamp| and |splice end timestamp|, compute the sum of a sample from |fade out samples| and the
              corresponding sample in |fade in samples| and store the result in |output samples|.</li>
            <li>Copy samples between |splice end timestamp| to |end timestamp| from |fade in samples| into |output samples|.</li>
            <li>Render |output samples|.</li>
          </ol>
          <div class="note">
            <p>Here is a graphical representation of this algorithm.</p>
            <img src="audio_splice.png" alt="Audio splice diagram">
          </div>
        </section>
        <section id="sourcebuffer-text-splice-frame-algorithm">
          <h4><dfn>Text Splice Frame</dfn></h4>
          <p>Follow these steps when the [=coded frame processing=] algorithm needs to generate a splice frame for two overlapping timed text
            [=coded frames=]:</p>
          <ol>
            <li>Let |track buffer| be the [=track buffer=] that will contain the splice.</li>
            <li>Let |new coded frame| be the new [=coded frame=], that is being added to |track buffer|, which triggered the need for a splice.</li>
            <li>Let |presentation timestamp:double| be the [=presentation timestamp=] for |new coded frame|</li>
            <li>Let |decode timestamp:double| be the decode timestamp for |new coded frame|.</li>
            <li>Let |frame duration:double| be the [=coded frame duration=] of |new coded frame|.</li>
            <li>Let |frame end timestamp:double| equal the sum of |presentation timestamp| and |frame duration|.</li>
            <li>Let |first overlapped frame| be the [=coded frame=] in |track buffer| with a [=presentation interval=] that contains |presentation timestamp|.
            </li>
            <li>Let |overlapped presentation timestamp:double| be the [=presentation timestamp=] of the |first overlapped frame|.</li>
            <li>Let |overlapped frames| equal |first overlapped frame| as well as any additional frames in |track buffer| that
              have a [=presentation timestamp=] greater than |presentation timestamp| and less than |frame end timestamp|.</li>
            <li>Remove all the frames included in |overlapped frames| from |track buffer|.
            </li><li>Update the [=coded frame duration=] of the |first overlapped frame| to |presentation timestamp| minus |overlapped presentation timestamp|.</li>
            <li>Add |first overlapped frame| to the |track buffer|.
            </li><li>Return to caller without providing a splice frame.
              <p class="note">This is intended to allow |new coded frame| to be added to the |track buffer| as if
                it hadn't overlapped any frames in |track buffer| to begin with.</p>
            </li>
          </ol>
        </section>
      </section>
    </section>

    <section id="sourcebufferlist">
      <h2><dfn>SourceBufferList</dfn> Object</h2>
      <p>SourceBufferList is a simple container object for <a>SourceBuffer</a> objects. It provides read-only array access and fires events when the list is modified.</p>
<pre class="idl">[Exposed=(Window,DedicatedWorker)]
interface SourceBufferList : EventTarget {
    readonly        attribute unsigned long length;
                    attribute EventHandler  onaddsourcebuffer;
                    attribute EventHandler  onremovesourcebuffer;
    getter SourceBuffer (unsigned long index);
};</pre>
      <section>
        <h2>Attributes</h2>
        <dl class="attributes" data-dfn-for="SourceBufferList">
          <dt><dfn><code>length</code></dfn> of type {{unsigned long}}, readonly       </dt>
          <dd>
            <p>Indicates the number of <a>SourceBuffer</a> objects in the list.</p>
          </dd>
          <dt><dfn><code>onaddsourcebuffer</code></dfn> of type {{EventHandler}}</dt>
          <dd>
            <p>The event handler for the {{addsourcebuffer}} event.</p>
          </dd>
          <dt><dfn><code>onremovesourcebuffer</code></dfn> of type {{EventHandler}}</dt>
          <dd>
            <p>The event handler for the {{removesourcebuffer}} event.</p>
          </dd>
        </dl>
      </section>
      <section>
        <h2>Methods</h2>
        <dl class="methods" data-dfn-for="SourceBufferList">
          <dt><dfn data-lt-noDefault data-lt="sourcebufferlist-getter"><code>getter</code></dfn></dt>
          <dd>
            <p>Allows the SourceBuffer objects in the list to be accessed with an array operator (i.e., []).</p>

            <ol class="method-algorithm">
              <li>If |index:unsigned long| is greater than or equal to the {{SourceBufferList/length}} attribute then return undefined and abort these steps.</li>
              <li>Return the |index|'th <a>SourceBuffer</a> object in the list.</li>
            </ol>
            <table class="parameters">
              <tbody>
                <tr><th>Parameter</th><th>Type</th><th>Nullable</th><th>Optional</th><th>Description</th></tr>
                <tr>
                  <td class="prmName">|index|</td>
                  <td class="prmType">{{unsigned long}}</td>
                  <td class="prmNullFalse"><span role="img" aria-label="False">✘</span></td>
                  <td class="prmOptFalse"><span role="img" aria-label="False">✘</span></td>
                  <td class="prmDesc"></td>
                </tr>
              </tbody>
            </table>
            <div><em>Return type: </em>{{SourceBuffer}}</div>
          </dd>
        </dl>
      </section>

      <section id="sourcebufferlist-events">
        <h3>Event Summary</h3>
        <table class="old-table">
          <thead>
            <tr>
              <th>Event name</th>
              <th>Interface</th>
              <th>Dispatched when...</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><dfn><code>addsourcebuffer</code></dfn></td>
              <td><code>Event</code></td>
              <td>When a <a>SourceBuffer</a> is added to the list.</td>
            </tr>
            <tr>
              <td><dfn><code>removesourcebuffer</code></dfn></td>
              <td><code>Event</code></td>
              <td>When a <a>SourceBuffer</a> is removed from the list.</td>
            </tr>
          </tbody>
        </table>
      </section>
    </section>

    <section id="htmlmediaelement-extensions">
      <h2>HTMLMediaElement Extensions</h2>
      <p>This section specifies what existing attributes on the {{HTMLMediaElement}} MUST return when a <a>MediaSource</a> is attached to the element.</p>

      <section id="htmlmediaelement-extensions-seekable">
        <h3>{{HTMLMediaElement}}.{{HTMLMediaElement/seekable}}</h3>
        <p>The {{HTMLMediaElement}}.{{HTMLMediaElement/seekable}} attribute returns a new static <a def-id="normalized-timeranges-object"></a> created based on the following steps:</p>
        <ol>
          <li>If the {{MediaSource}} was constructed in a
            {{DedicatedWorkerGlobalScope}} that is terminated or is closing
            then return an empty {{TimeRanges}} object and abort these steps.
            <p class="note">
              This case is intended to handle implementations that may no
              longer maintain any previous information about buffered or
              seekable media in a MediaSource that was constructed in a
              DedicatedWorkerGlobalScope that has been terminated by
              {{Worker/terminate()}} or user agent execution of [=terminate a
              worker=] for the MediaSource's DedicatedWorkerGlobalScope, for
              instance as the eventual result of
              {{DedicatedWorkerGlobalScope/close()}} execution.
            </p>
            <div class="issue" data-number="277">
              <p>Should there be some (eventual) media element error transition
              in the case of an attached worker MediaSource having its context
              destroyed? The experimental Chromium implementation of worker MSE
              just keeps the element readyState, networkState and error the
              same as prior to that context destruction, though the seekable
              and buffered attributes each report an empty TimeRange.</p>
            </div>
          </li>

          <li>Let |recent duration:unrestricted double| and |recent live seekable range:normalized TimeRanges|
            respectively be the recent values of {{MediaSource/duration}} and {{MediaSource/[[live seekable range]]}},
            determined as follows:
            <dl class="switch">
              <dt>If the {{MediaSource}} was constructed in a {{Window}}</dt>
              <dd>Set |recent duration| to be {{MediaSource/duration}} and set |recent live seekable range| to be
                {{MediaSource/[[live seekable range]]}}.</dd>
              <dt>Otherwise:</dt>
              <dd>Set |recent duration| and |recent live seekable range| respectively to be what the
                {{MediaSource/duration}} and {{MediaSource/[[live seekable range]]}} were recently, updated by handling
                implicit messages posted by the {{MediaSource}} to its {{MediaSource/[[port to main]]}} on every change
                to {{MediaSource/duration}} or {{MediaSource/[[live seekable range]]}}.</dd>
            </dl>
          </li>
          <li>
            <dl class="switch">
              <dt>If |recent duration| equals NaN:</dt>
              <dd>Return an empty {{TimeRanges}} object.</dd>
              <dt>If |recent duration| equals positive Infinity:</dt>
              <dd>
                <ol>
                  <li>If |recent live seekable range| is not empty:
                    <ol>
                      <li>Let |union ranges:normalized TimeRanges| be the union of |recent live seekable range| and the
                        {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} attribute.</li>
                      <li>Return a single range with a start time equal to the earliest start time in |union ranges| and
                        an end time equal to the highest end time in |union ranges| and abort these steps.</li>
                    </ol>
                  </li>
                  <li>If the {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} attribute returns an empty {{TimeRanges}}
                    object, then return an empty {{TimeRanges}} object and abort these steps.</li>
                  <li>Return a single range with a start time of 0 and an end time equal to the highest end time
                    reported by the {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} attribute.
              </li></ol></dd>
              <dt>Otherwise:</dt>
              <dd>Return a single range with a start time of 0 and an end time equal to |recent duration|.</dd>
            </dl>
          </li>
        </ol>
      </section>

      <section id="htmlmediaelement-extensions-buffered">
        <h3>{{HTMLMediaElement}}.{{HTMLMediaElement/buffered}}</h3>
        <p id="dom-htmlmediaelement.buffered">The {{HTMLMediaElement}}.{{HTMLMediaElement/buffered}} attribute returns a static <a def-id="normalized-timeranges-object"></a> based on the following steps.</p>
        <ol>
          <li>If the {{MediaSource}} was constructed in a
            {{DedicatedWorkerGlobalScope}} that is terminated or is closing
            then return an empty {{TimeRanges}} object and abort these steps.
            <p class="note">
              This case is intended to handle implementations that may no
              longer maintain any previous information about buffered or
              seekable media in a MediaSource that was constructed in a
              DedicatedWorkerGlobalScope that has been terminated by
              {{Worker/terminate()}} or user agent execution of [=terminate a
              worker=] for the MediaSource's DedicatedWorkerGlobalScope, for
              instance as the eventual result of
              {{DedicatedWorkerGlobalScope/close()}} execution.
            </p>
            <div class="issue" data-number="277">
              <p>Should there be some (eventual) media element error transition
              in the case of an attached worker MediaSource having its context
              destroyed? The experimental Chromium implementation of worker MSE
              just keeps the element readyState, networkState and error the
              same as prior to that context destruction, though the seekable
              and buffered attributes each report an empty TimeRange.</p>
            </div>
          </li>

          <li>Let |recent intersection ranges:normalized TimeRanges| be determined as follows:
            <dl class="switch">
              <dt>If the {{MediaSource}} was constructed in a {{Window}}</dt>
              <dd>
              <ol>
                <li>Let |recent intersection ranges| equal an empty {{TimeRanges}} object.</li>
                <li>If {{MediaSource/activeSourceBuffers}}.length does not equal 0 then run the following steps:
                  <ol>
                    <li>Let |active ranges:sequence of normalized TimeRanges| be the ranges returned by
                      {{SourceBuffer/buffered}} for each <a>SourceBuffer</a> object in
                      {{MediaSource/activeSourceBuffers}}.</li>
                    <li>Let |highest end time:unrestricted double| be the largest range end time in the
                      |active ranges|.</li>
                    <li>Let |recent intersection ranges:normalized TimeRanges| equal a {{TimeRanges}} object containing
                      a single range from 0 to |highest end time|.</li>
                    <li>For each <a>SourceBuffer</a> object in {{MediaSource/activeSourceBuffers}} run the following
                      steps:
                      <ol>
                        <li>Let |source ranges:normalized TimeRanges| equal the ranges returned by the
                          {{SourceBuffer/buffered}} attribute on the current <a>SourceBuffer</a>.</li>
                        <li>If {{MediaSource/readyState}} is {{ReadyState/""ended""}}, then set the end time on the last
                          range in |source ranges| to |highest end time|.</li>
                        <li>Let |new intersection ranges:normalized TimeRanges| equal the intersection between the
                          |recent intersection ranges| and the |source ranges|.</li>
                        <li>Replace the ranges in |recent intersection ranges| with the |new intersection ranges|.</li>
                      </ol>
                    </li>
                  </ol>
                </li>
              </ol>
              </dd>
              <dt>Otherwise:</dt>
              <dd>Let |recent intersection ranges| be the {{TimeRanges}} resulting from the steps for the
              {{Window}} case, but run with the {{MediaSource}} and its {{SourceBuffer}} objects in their
              {{DedicatedWorkerGlobalScope}} and communicated by using {{MediaSource/[[port to main]]}} implicit
              messages on every update to the {{MediaSource/activeSourceBuffers}}, {{MediaSource/readyState}}, or any of
              the buffering state that would change any of the values of each of those {{SourceBuffer/buffered}}
              attributes of the {{MediaSource/activeSourceBuffers}}.
              <p class="note">The overhead of recalculating and communicating |recent intersection ranges| so
              frequently is one reason for allowing implementation flexibility to query this information on-demand using
              other mechanisms such as shared memory and locks as mentioned in [=cross-context communication
              model=].</p>
              </dd>
            </dl>
          </li>
          <li>If the current value of this attribute has not been set by this algorithm or
            |recent intersection ranges| does not contain the exact same range information as the
            current value of this attribute, then update the current value of this attribute to
            |recent intersection ranges|.
          </li><li>Return the current value of this attribute.</li>
        </ol>
      </section>
    </section>

    <section id="audio-track-extensions">
      <h2>AudioTrack Extensions</h2>
      <p>This section specifies extensions to the [[HTML]] {{AudioTrack}} definition.</p>
      <div><pre class="idl">[Exposed=(Window,DedicatedWorker)]
partial interface AudioTrack {
    readonly        attribute SourceBuffer? sourceBuffer;
};</pre>
        <div class="issue" data-number="280">[[HTML]] {{AudioTrack}} needs Window+DedicatedWorker
          exposure.</div>
        <section><h2>Attributes</h2><dl class="attributes" data-dfn-for="AudioTrack"><dt><dfn><code>sourceBuffer</code></dfn> of type <span class="idlAttrType"><a>SourceBuffer</a></span>, readonly       , nullable</dt><dd>
        <p>On getting, run the following step:
            <dl class="switch">
              <dt>If this track was created by a {{SourceBuffer}} that was created on the same [=global object/realm=]
              as this track, and if that {{SourceBuffer}} has not been removed from the {{MediaSource/sourceBuffers}}
              attribute of its [=parent media source=]:</dt>
              <dd>Return the {{SourceBuffer}} that created this track.</dd>
              <dt>Otherwise:</dt>
              <dd>Return null.</dd>
            </dl>
            <div class="note">
              For example, if a {{DedicatedWorkerGlobalScope}} {{SourceBuffer}} notified its internal <code>create track
              mirror</code> handler in {{Window}} to create this track, then the {{Window}} copy of the track would
              return null for this attribute.
            </div>
          </div>
        </p>
        </dd></dl></section></div>
    </section>

    <section id="video-track-extensions">
      <h2>VideoTrack Extensions</h2>
      <p>This section specifies extensions to the [[HTML]] {{VideoTrack}} definition.</p>

      <div><pre class="idl">[Exposed=(Window,DedicatedWorker)]
partial interface VideoTrack {
    readonly        attribute SourceBuffer? sourceBuffer;
};</pre>
        <div class="issue" data-number="280">[[HTML]] {{VideoTrack}} needs Window+DedicatedWorker
          exposure.</div>
        <section><h2>Attributes</h2><dl class="attributes" data-dfn-for="VideoTrack"><dt><dfn><code>sourceBuffer</code></dfn> of type <span class="idlAttrType"><a>SourceBuffer</a></span>, readonly       , nullable</dt><dd>
        <p>On getting, run the following step:
            <dl class="switch">
              <dt>If this track was created by a {{SourceBuffer}} that was created on the same [=global object/realm=]
              as this track, and if that {{SourceBuffer}} has not been removed from the {{MediaSource/sourceBuffers}}
              attribute of its [=parent media source=]:</dt>
              <dd>Return the {{SourceBuffer}} that created this track.</dd>
              <dt>Otherwise:</dt>
              <dd>Return null.</dd>
            </dl>
            <div class="note">
              For example, if a {{DedicatedWorkerGlobalScope}} {{SourceBuffer}} notified its internal <code>create track
              mirror</code> handler in {{Window}} to create this track, then the {{Window}} copy of the track would
              return null for this attribute.
            </div>
          </div>
        </p>
        </dd></dl></section></div>
    </section>

    <section id="text-track-extensions">
      <h2>TextTrack Extensions</h2>
      <p>This section specifies extensions to the [[HTML]] {{TextTrack}} definition.</p>

      <div><pre class="idl">[Exposed=(Window,DedicatedWorker)]
partial interface TextTrack {
    readonly        attribute SourceBuffer? sourceBuffer;
};</pre>
        <div class="issue" data-number="280">[[HTML]] {{TextTrack}} needs Window+DedicatedWorker
          exposure.</div>
        <section><h2>Attributes</h2><dl class="attributes" data-dfn-for="TextTrack"><dt><dfn><code>sourceBuffer</code></dfn> of type <span class="idlAttrType"><a>SourceBuffer</a></span>, readonly       , nullable</dt><dd>
        <p>On getting, run the following step:
            <dl class="switch">
              <dt>If this track was created by a {{SourceBuffer}} that was created on the same [=global object/realm=]
              as this track, and if that {{SourceBuffer}} has not been removed from the {{MediaSource/sourceBuffers}}
              attribute of its [=parent media source=]:</dt>
              <dd>Return the {{SourceBuffer}} that created this track.</dd>
              <dt>Otherwise:</dt>
              <dd>Return null.</dd>
            </dl>
            <div class="note">
              For example, if a {{DedicatedWorkerGlobalScope}} {{SourceBuffer}} notified its internal <code>create track
              mirror</code> handler in {{Window}} to create this track, then the {{Window}} copy of the track would
              return null for this attribute.
            </div>
          </div>
        </p>
        </dd></dl></section></div>
    </section>

    <section id="byte-stream-formats">
      <h2><dfn data-export="">Byte Stream Formats</dfn></h2>
      <p>The bytes provided through {{SourceBuffer/appendBuffer()}} for a <a>SourceBuffer</a> form a logical byte stream. The format and
        semantics of these byte streams are defined in <dfn id="byte-stream-format-specs">byte stream format specifications</dfn>.
        The byte stream format registry [[MSE-REGISTRY]] provides mappings between a MIME type that may be passed to {{MediaSource/addSourceBuffer()}},
        {{MediaSource/isTypeSupported()}} or {{SourceBuffer/changeType()}} and the byte stream format expected by a {{SourceBuffer}} using that
        MIME type for parsing newly appended data. Implementations are encouraged to register
        mappings for byte stream formats they support to facilitate interoperability. The byte stream format registry [[MSE-REGISTRY]] is the authoritative source for these
        mappings. If an implementation claims to support a MIME type listed in the registry, its <a>SourceBuffer</a> implementation MUST conform to the
        [=byte stream format specification=] listed in the registry entry.</p>
      <p class="note">The byte stream format specifications in the registry are not intended to define new storage formats. They simply outline the subset of
        existing storage format structures that implementations of this specification will accept.</p>
      <p class="note">Byte stream format parsing and validation is implemented in the [=segment parser loop=] algorithm.</p>

      <p>This section provides general requirements for all byte stream format specifications:</p>
      <ul>
        <li>A byte stream format specification MUST define [=initialization segments=] and [=media segments=].</li>
        <li>A byte stream format SHOULD provide references for sourcing {{AudioTrack}}, {{VideoTrack}}, and {{TextTrack}} attribute values
          from data in [=initialization segments=].
          <p class="note">If the byte stream format covers a format similar to one covered in the in-band tracks spec [[INBANDTRACKS]], then
            it SHOULD try to use the same attribute mappings so that Media Source Extensions playback and non-Media Source Extensions playback provide the
            same track information.</p>
        </li>
        <li>It MUST be possible to identify segment boundaries and segment type (initialization or media) by examining the byte stream alone.</li>
        <li>The user agent MUST run the [=append error=] algorithm when any of the following conditions are met:
          <ol>
            <li>
              <p>The number and type of tracks are not consistent.</p>
              <p class="note">For example, if the first [=initialization segment=] has 2 audio tracks and 1 video track, then all [=initialization segments=] that follow it in the byte stream MUST describe 2 audio tracks and 1 video track.</p>
            </li>
            <li>[=Track IDs=] are not the same across [=initialization segments=], for segments describing multiple tracks of a single type (e.g., 2 audio tracks).</li>
            <li>
              <p>Unsupported codec changes occur across [=initialization segments=].</p>
              <p class="note">See the [=initialization segment received=] algorithm, {{MediaSource/addSourceBuffer()}} and {{SourceBuffer/changeType()}} for details and examples of codec changes.</p>
            </li>
          </ol>
        </li>
        <li>The user agent MUST support the following:
          <ol>
            <li>[=Track IDs=] changing across [=initialization segments=] if the segments describe only one track of each type.</li>
            <li>
              <p>Video frame size changes. The user agent MUST support seamless playback.</p>
              <p class="note">This will cause the &lt;video&gt; display region to change size if the web application does not use CSS or HTML attributes (width/height) to constrain the element size.</p>
            </li>
            <li>
              <p>Audio channel count changes. The user agent MAY support this seamlessly and could trigger downmixing.</p>
              <p class="note">This is a quality of implementation issue because changing the channel count may require reinitializing the audio device, resamplers, and channel mixers which tends to be audible.</p>
            </li>
          </ol>
        </li>
        <li>The following rules apply to all [=media segments=] within a byte stream. A user agent MUST:
          <ol>
            <li>Map all timestamps to the same <a def-id="media-timeline"></a>.</li>
            <li>Support seamless playback of [=media segments=] having a timestamp gap smaller than the audio frame size. User agents MUST NOT reflect these gaps in the {{SourceBuffer/buffered}} attribute.
              <p class="note">This is intended to simplify switching between audio streams where the frame boundaries don't always line up across encodings (e.g., Vorbis).</p>
            </li>
          </ol>
        </li>
        <li>The user agent MUST run the [=append error=] algorithm when any combination of an [=initialization segment=] and any contiguous sequence of [=media segments=] satisfies the
          following conditions:
          <ol>
            <li>The number and type (audio, video, text, etc.) of all tracks in the [=media segments=] are not identified.</li>
            <li>The decoding capabilities needed to decode each track (i.e., codec and codec parameters) are not provided.</li>
            <li>Encryption parameters necessary to decrypt the content (except the encryption key itself) are not provided for all encrypted tracks.</li>
            <li>All information necessary to decode and render the earliest [=random access point=] in the sequence of [=media segments=] and all subsequence samples in the sequence
              (in presentation time) are not provided. This includes in particular,
              <ul>
                <li>Information that determines the <a def-id="intrinsic-width-and-height"></a> of the video (specifically, this requires either the picture or pixel aspect ratio, together with the encoded
                  resolution).</li>
                <li>Information necessary to convert the video decoder output to a format suitable for display</li>
              </ul>
            </li>
            <li>Information necessary to compute the global [=presentation timestamp=] of every sample in the sequence of [=media segments=] is not provided.</li>
          </ol>
          <p>For example, if I1 is associated with M1, M2, M3 then the above MUST hold for all the combinations I1+M1, I1+M2, I1+M1+M2, I1+M2+M3, etc.</p>
        </li>
      </ul>
      <p>Byte stream specifications MUST at a minimum define constraints which ensure that the above requirements hold. Additional constraints MAY be defined, for example to simplify implementation.</p>

    </section>

    <section id="conformance"></section>

    <section id="examples">
      <h2>Examples</h2>
      <p>Example use of the Media Source Extensions</p>
      <div class="block">
        <div class="blockContent">
          <pre class="code">&lt;script&gt;
  function onSourceOpen(videoTag, e) {
    var mediaSource = e.target;

    if (mediaSource.sourceBuffers.length &gt; 0)
        return;

    var sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');

    videoTag.addEventListener('seeking', onSeeking.bind(videoTag, mediaSource));
    videoTag.addEventListener('progress', onProgress.bind(videoTag, mediaSource));

    var initSegment = GetInitializationSegment();

    if (initSegment == null) {
      // Error fetching the initialization segment. Signal end of stream with an error.
      mediaSource.endOfStream("network");
      return;
    }

    // Append the initialization segment.
    var firstAppendHandler = function(e) {
      var sourceBuffer = e.target;
      sourceBuffer.removeEventListener('updateend', firstAppendHandler);

      // Append some initial media data.
      appendNextMediaSegment(mediaSource);
    };
    sourceBuffer.addEventListener('updateend', firstAppendHandler);
    sourceBuffer.appendBuffer(initSegment);
  }

  function appendNextMediaSegment(mediaSource) {
    if (mediaSource.readyState == "closed")
      return;

    // If we have run out of stream data, then signal end of stream.
    if (!HaveMoreMediaSegments()) {
      mediaSource.endOfStream();
      return;
    }

    // Make sure the previous append is not still pending.
    if (mediaSource.sourceBuffers[0].updating)
        return;

    var mediaSegment = GetNextMediaSegment();

    if (!mediaSegment) {
      // Error fetching the next media segment.
      mediaSource.endOfStream("network");
      return;
    }

    // NOTE: If mediaSource.readyState == “ended”, this appendBuffer() call will
    // cause mediaSource.readyState to transition to "open". The web application
    // should be prepared to handle multiple “sourceopen” events.
    mediaSource.sourceBuffers[0].appendBuffer(mediaSegment);
  }

  function onSeeking(mediaSource, e) {
    var video = e.target;

    if (mediaSource.readyState == "open") {
      // Abort current segment append.
      mediaSource.sourceBuffers[0].abort();
    }

    // Notify the media segment loading code to start fetching data at the
    // new playback position.
    SeekToMediaSegmentAt(video.currentTime);

    // Append a media segment from the new playback position.
    appendNextMediaSegment(mediaSource);
  }

  function onProgress(mediaSource, e) {
    appendNextMediaSegment(mediaSource);
  }
&lt;/script&gt;

&lt;video id="v" autoplay&gt; &lt;/video&gt;

&lt;script&gt;
  var video = document.getElementById('v');
  var mediaSource = new MediaSource();
  mediaSource.addEventListener('sourceopen', onSourceOpen.bind(this, video));
  video.src = window.URL.createObjectURL(mediaSource);
&lt;/script&gt;
          </pre>
        </div>
      </div>
    </section>


    <section id="acknowledgements">
      <h2>Acknowledgments</h2>
      The editors would like to thank <a def-id="contributors"></a> for their contributions to this specification.
    </section>

    <section id="VideoPlaybackQuality" class="appendix informative">
      <h2>VideoPlaybackQuality</h2>
      The video playback quality metrics described in previous revisions of this specification (e.g., sections 5 and 10 of the <a href="https://www.w3.org/TR/2016/CR-media-source-20160705/">Candidate Recommendation</a>) are now being developed as part of [[MEDIA-PLAYBACK-QUALITY]]. Some implementations may have implemented the earlier draft <code>VideoPlaybackQuality</code> object and the {{HTMLVideoElement}} extension method <code>getVideoPlaybackQuality()</code> described in those previous revisions.
    </section>

    <section class="appendix" id="issue-summary">
      <!-- A list of issues will magically appear here -->
    </section>
  </body>
</html>
